微信小程序五子棋游戲AI實現(xiàn)方法【附demo源碼下載】
本文實例講述了微信小程序五子棋游戲AI實現(xiàn)方法。分享給大家供大家參考,具體如下:
DEMO下載
效果圖
原理
1. 將棋盤中能夠勝利的五子連珠方法遍歷一個數(shù)組;
2. 當(dāng)AI持棋時,遍歷棋盤中所有棋子的空位;
3. 如果用戶落子該位置,給用戶該位置的五連珠方式進(jìn)行加分:1連10分,2連20分,3連40分,4連80分;
4. 如果AI落子該位置,給AI該位置的五連珠方式進(jìn)行加分:1連15分,2連25分,3連45分,4連85分;
5. 最后對該位置的分值進(jìn)行比較,取最大分值位置的坐標(biāo),AI在最大分值位落子。
AI代碼
computerAI(){ var playerScore = [],computerScore = []; var max = 0,u = 0, v = 0; for (var i = 0; i < this.type; i++){ playerScore[i] = []; computerScore[i] = []; for (var j = 0; j < this.type; j++){ playerScore[i][j] = 0; computerScore[i][j] = 0; } } for (var x = 0; x < this.type; x++) { for (var y = 0; y < this.type; y++) { var po = this.checkPosition(x, y); if (po.status == 0){ for (var k = 0; k < this.count; k++) { if (this.WIN_ARRAY[x][y][k]){ if (this.player[k] == 1){ playerScore[x][y] += 10; } else if (this.player[k] == 2){ playerScore[x][y] += 20; } else if (this.player[k] == 3) { playerScore[x][y] += 40; } else if (this.player[k] == 4) { playerScore[x][y] += 80; } if (this.computer[k] == 1) { computerScore[x][y] += 15; } else if (this.player[k] == 2) { computerScore[x][y] += 25; } else if (this.player[k] == 3) { computerScore[x][y] += 45; } else if (this.player[k] == 4) { computerScore[x][y] += 85; } } } if (playerScore[x][y] > max){ max = playerScore[x][y]; u = x; v = y; } else if (playerScore[x][y] == max){ if (computerScore[x][y] > computerScore[u][v]){ u = x; v = y; } } if (computerScore[x][y] > max) { max = computerScore[x][y]; u = x; v = y; } else if (computerScore[x][y] == max) { if (playerScore[x][y] > playerScore[u][v]) { u = x; v = y; } } } } } var point = this.checkPosition(u,v); if(point.status == 0){ this.oneStep(point); point.status = -1; this.COMPUTER_ARRAY.push(point); for (var i = 0; i < this.count; i++) { if (this.WIN_ARRAY[point.pointX][point.pointY][k]) { this.computer[k]++; this.player[k] = 100; } } if (point.status == -1 && this.COMPUTER_ARRAY.length >= this.CHESS_LEN && this.checkWin(point, this.COMPUTER_ARRAY)) { wx.showToast({ title: '白棋勝利!' }); this.isStart = false; } if (this.isStart) { this.isWho = !this.isWho; } } }
注意
此種方式實現(xiàn)的算法AI的防守比較重,進(jìn)攻性不強,有待優(yōu)化。而且很簡單就能給AI設(shè)置陷阱而取得勝。
希望本文所述對大家微信小程序開發(fā)有所幫助。
相關(guān)文章
JavaScript實現(xiàn)iframe自動高度調(diào)整和不同主域名跨域
這篇文章主要介紹了JavaScript實現(xiàn)iframe自動高度調(diào)整和不同主域名跨域,作者通過建立一個代理來同步高度調(diào)整,需要的朋友可以參考下2016-02-02JavaScript類型系統(tǒng)之正則表達(dá)式
正則又叫規(guī)則或模式,是一個強大的字符串匹配工具。javascript通過RegExp類型來支持正則表達(dá)式,本文給大家介紹javascript類型系統(tǒng)之正則表達(dá)式,對js正則表達(dá)式相關(guān)知識感興趣的朋友一起學(xué)習(xí)吧2016-01-01js鎖屏解屏通過對$.ajax進(jìn)行封裝實現(xiàn)
js鎖屏解屏是通過對$.ajax進(jìn)行封裝實現(xiàn)的,需要的朋友可以參考下2014-07-07Bootstrap 3的box-sizing樣式導(dǎo)致UEditor控件的圖片無法正常縮放的解決方案
這篇文章主要介紹了Bootstrap 3的box-sizing樣式導(dǎo)致UEditor控件的圖片無法正??s放的解決方案的相關(guān)資料,需要的朋友可以參考下2016-09-09Js 回車換行處理的辦法及replace方法應(yīng)用
當(dāng)我們在文本框里輸入文字敲下回車后,希望在提交后網(wǎng)頁也顯示是換行的效果,可往往并不能如愿以償啊,實在是憤怒啊自己寫了一個回車換行處理的函數(shù),感興趣的朋友可以了解下啊,希望本文對你有所幫助2013-01-01