本文實例講述了微信小程序五子棋游戲AI實現方法。分享給大家供大家參考,具體如下:
DEMO下載
效果圖
原理
1. 將棋盤中能夠勝利的五子連珠方法遍歷一個數組;
2. 當AI持棋時,遍歷棋盤中所有棋子的空位;
3. 如果用戶落子該位置,給用戶該位置的五連珠方式進行加分:1連10分,2連20分,3連40分,4連80分;
4. 如果AI落子該位置,給AI該位置的五連珠方式進行加分:1連15分,2連25分,3連45分,4連85分;
5. 最后對該位置的分值進行比較,取最大分值位置的坐標,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; } } }
注意
此種方式實現的算法AI的防守比較重,進攻性不強,有待優化。而且很簡單就能給AI設置陷阱而取得勝。
希望本文所述對大家微信小程序開發有所幫助。
新聞熱點
疑難解答