我有一个 6 x 6 的游戏板,由以下数组表示:
gameBoard= [
0 , 1, 2, 3, 4, 5,
6 , 7, 8, 9,10,11,
12,13,14,15,16,17,
18,19,20,21,22,23,
24,25,26,27,28,29,
30,31,32,33,34,35
]
我正在开发一款混合井字游戏。
这是第一步(轮到CPU):
循环遍历棋盘的每个位置
for(var i=0, len = gameBoard.length; i < len; i++){
}
现在,假设我在第 8 位。
我的逻辑是检查周围的位置(1,2,3,7,9,13,14,15):
- 如果有“X”(对手),则得分 = 0;
- 如果有空格,sc0re = 1;
- 如果有“0”,则得分 = 2
最后,将所有内容存储在数组中。
该数组中得分最高的位置将是 CPU 将播放的位置。
最后,问题是:您将如何在 for 循环中编写上述逻辑?,请记住,像 0,1,2,4... 这样的位置并没有被其他位置包围,所以我们不能在任何地方使用上面的逻辑。
以下是我尝试和考虑的基础:
function scoreCalc(pos){
console.log("score: "+pos);
var score = 0,
pocket;
pocket = jQuery(document).find('[data-kcpos="'+pos+'"]');
if(jQuery(pocket).hasClass("blank")){
score += 1;
} else if(jQuery(pocket).text() == "x"){
score += 0;
} else if(jQuery(pocket).text() == "0"){
score += 2;
}
console.log("score: "+score);
return score;
}
function minimax(){
var pos,
testMargin,
toTest,
pocket,
score,
toTestScore,
totalScore = new Array();
for(var i=0, len = gameBoard.length; i < len; i++){
score = 0;
pos = gameBoard[i];
// Check if pocket is empty
pocket = jQuery(document).find('[data-kcpos="'+pos+'"]');
if(jQuery(pocket).hasClass("blank")){
// Check to see if we have a margin
testMargin = jQuery.inArray(pos, margins);
if(testMargin != -1){ // If we have a margin
} else {
// Test the pocket above
toTest = pos - 6;
toTestScore = scoreCalc(toTest);
score += toTestScore;
// Test the pocket bellow
toTest = pos + 6;
toTestScore = scoreCalc(toTest);
score += toTestScore;
// Test the pocket to the left
toTest = pos - 1;
toTestScore = scoreCalc(toTest);
score += toTestScore;
// Test the pocket to the right
toTest = pos + 1;
toTestScore = scoreCalc(toTest);
score += toTestScore;
// Test the top left diagonal
toTest = pos - 7;
toTestScore = scoreCalc(toTest);
score += toTestScore;
// Test the bottom right diagonal
toTest = pos + 7;
toTestScore = scoreCalc(toTest);
score += toTestScore;
// Test the top right diagonal
toTest = pos - 5;
toTestScore = scoreCalc(toTest);
score += toTestScore;
// Test the bottom left diagonal
toTest = pos + 5;
toTestScore = scoreCalc(toTest);
score += toTestScore;
}
totalScore.push({key: pos, val: score});
}
}
// Sort the array
totalScore.sort(function descending(a,b){
return b.val - a.val;
});
pocket = jQuery(document).find('[data-kcpos="'+totalScore[0].key+'"]');
jQuery(pocket).find(".ui-btn-text").text("0");
jQuery(pocket).removeClass("blank");
return totalScore;
}