微信小程序五子棋游戲AI實現(xiàn)方法【附demo源碼下載】
本文實例講述了微信小程序五子棋游戲AI實現(xiàn)方法。分享給大家供大家參考,具體如下:
DEMO下載
效果圖

原理
1. 將棋盤中能夠勝利的五子連珠方法遍歷一個數(shù)組;
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;
}
}
}
注意
此種方式實現(xiàn)的算法AI的防守比較重,進攻性不強,有待優(yōu)化。而且很簡單就能給AI設置陷阱而取得勝。
希望本文所述對大家微信小程序開發(fā)有所幫助。
相關文章
微信小程序setInterval定時函數(shù)新手使用的超詳細教程
平時開發(fā)中為實現(xiàn)倒計時效果可以使用setInterval即可,下面這篇文章主要給大家介紹了關于微信小程序setInterval定時函數(shù)新手使用的超詳細教程,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-08-08
由document.body和document.documentElement想到的
不知道大家對這個標題有沒有想法,反正此前我一直把他們混為了一談。其實不然,首先需有個“標準”的概念。2009-04-04
JS實現(xiàn)仿google、百度搜索框輸入信息智能提示的實現(xiàn)方法
這篇文章主要介紹了JS實現(xiàn)仿google、百度搜索框輸入信息智能提示的實現(xiàn)方法,實例分析了javascript實現(xiàn)智能提示功能的技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04

