我正在寻找一种使用for循环或替代解决方案来检查Tic Tac Toe冠军的好方法。
到目前为止我尝试过的循环是这个
$(document).ready(function() {
var huPlayer, computer;
var huPlayerArr = [], computerArr = [];
var occupiedCells = [];
var winningCombos = [
[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]
];
$cell = $('.cell');
$('#myModal').modal('show');
$('.select').click(function() {
let turnX = 'X';
let turnO = 'O';
$(this).attr("data-dismiss", "modal");
huPlayer = $(this).text()
computer = huPlayer === turnX ? turnO: turnX;
$('.player').append(`<div class="alert-success">You chose to play as ${huPlayer}</div>`);
});
function resetGame() {
huPlayer = undefined;
computer = undefined;
huPlayerArr = [];
computerArr = [];
occupiedCells = [];
}
// Min max function
function generateRandomNumber(min, max) {
return Math.floor(Math.random()*(max-min+1)+min);
}
function isEmpty(el) {
if ($.trim($(el).html()) == '') {
return true;
};
}
function insertMarker(text, val, id) {
occupiedCells.push(+id);
text.html(val);
}
// Check winner
function isThereAWinner(arr) {
for (let i = 0; i < winningCombos.length; i++) {
if (arr.indexOf(winningCombos[i][0] == 1)
&& arr.indexOf(winningCombos[i][1] == 1
&& arr.indexOf(winningCombos[i][0] == 1))) {
console.log("There's a winner");
}
}
}
$cell.click(function() {
if (huPlayer === undefined && computer === undefined) {
$('#myModal').modal('show');
}
else {
var id = $(this).attr("id");
if (isEmpty(id)) {
insertMarker($(this), huPlayer, id);
huPlayerArr.push(id);
console.log(huPlayerArr);
if (isThereAWinner(huPlayerArr)) {
console.log("There's a winner");
}
else if (occupiedCells.length === 9) {
console.log("Tie game");
}
}
}
});
});
我希望人类玩家每次在单元格中单击时都调用此函数,然后AI应该随机插入一个标记。我不确定如何为AI实现min max功能。
对于每个winningCombos
数组,如果在arr
中存在该获胜组合中的三个正方形ID,则您有一个获胜者:
function isThereAWinner(arr) {
for (let i = 0; i < winningCombos.length; i++) {
if (
arr.includes( winningCombos[i][0] )
&&
arr.includes( winningCombos[i][1] )
&&
arr.includes( winningCombos[i][2] )
) {
console.log("There's a winner");
break;
}
}