算法代码设计
五子棋的内层算法决定了人工智能五子棋的反应速度和下棋实力。通过数值搜索算法,以尽量快的响应速度,让玩家感受不到延迟。不断的对算法进行优化,提高人工智能五子棋的棋力水平达到超过一般人水准。
人工智能五子棋赢法算法如下:
var Chessboard = function(row, column) {
this.data = [];
this.row = row;
this.column = column;
//赢法数组
this.wins = [];
//赢法数
this.count = 0;
//记录max每一种赢法的已经达成棋子数
this.maxWin = [];
//记录min每一种赢法的已经达成棋子数
this.minWin = [];
//初始化棋盘,顺便初始化赢法数组
for (var i = 0; i < row; i++) {
this.data[i] = [];
this.wins[i] = [];
for (var j = 0; j < column; j++) {
this.data[i][j] = Chessboard.NONE;
this.wins[i][j] = [];
}
}
//横向赢法
for (var i = 0; i < row; i++) {
for (var j = 0; j <= column - 5; j++) {
for (var k = 0; k < 5; k++) {
this.wins[i][j + k][this.count] = true;
}
this.count++;
}
}
//纵向赢法
for (var i = 0; i < column; i++) {
for (var j = 0; j <= row - 5; j++) {
for (var k = 0; k < 5; k++) {
this.wins[j + k][i][this.count] = true;
}
this.count++;
}
}
//右斜线的赢法
for (var i = 0; i <= row - 5; i++) {
for (var j = 0; j <= column - 5; j++) {
for (var k = 0; k < 5; k++) {
this.wins[i + k][j + k][this.count] = true;
}
this.count++;
}
}
//左斜线的赢法
for (var i = 0; i <= row - 5; i++) {
for (var j = column - 1; j >= 4; j--) {
for (var k = 0; k < 5; k++) {
this.wins[i + k][j - k][this.count] = true;
}
this.count++;
}
}
//初始化max和min每一种赢法的下子情况
for (var i = 0; i < this.count; i++) {
this.maxWin[i] = {
max: 0,
min: 0
};
this.minWin[i] = {
min: 0,
max: 0
};
}
人工智能对各个位置落子的胜算估值部分代码如下:
Chessboard.prototype.evaluate = function() {
var maxW = minW = 0;
var maxGroup = {
"5": 0,
"4": 0,
"3": 0,
"2": 0,
"1": 0
},
minGroup = {
"5": 0,
"4": 0,
"3": 0,
"2": 0,
"1": 0
};
for (var i = 0; i < this.count; i++) {
if (this.maxWin[i].max == 5 && !this.maxWin[i].min) {
return Chessboard.MAX_VALUE;
}
if (this.minWin[i].min == 5 && !this.minWin[i].max) {
return Chessboard.MIN_VALUE;
}
if (this.maxWin[i].max == 4 && !this.maxWin[i].min) {
maxGroup[4]++;
}
if (this.minWin[i].min == 4 && !this.minWin[i].max) {
minGroup[4]++;
}
if (this.maxWin[i].max == 3 && !this.maxWin[i].min) {
maxGroup[3]++;
}
if (this.minWin[i].min == 3 && !this.minWin[i].max) {
minGroup[3]++;
}
if (this.maxWin[i].max == 2 && !this.maxWin[i].min) {
maxGroup[2]++;
}
if (this.minWin[i].min == 2 && !this.minWin[i].max) {
minGroup[2]++;
}
if (this.maxWin[i].max == 1 && !this.maxWin[i].min) {
maxGroup[1]++;
}
if (this.minWin[i].min == 1 && !this.minWin[i].max) {
minGroup[1]++;
}
}
maxW = maxGroup[4] * Chessboard.FOUR_W + maxGroup[3] * Chessboard.THREE_W + maxGroup[2] * Chessboard.TWO_W + maxGroup[1] * Chessboard.ONE_W;
minW = minGroup[4] * Chessboard.FOUR_W + minGroup[3] * Chessboard.THREE_W + minGroup[2] * Chessboard.TWO_W + minGroup[1] * Chessboard.ONE_W;
return maxW - minW;
};
标签:minWin,游戏,min,人工智能,max,Chessboard,五子棋,++,var From: https://www.cnblogs.com/yenaibo/p/17134945.html