我正在创建一个tictactoe游戏,并试图将winPattern 2d数组中的每个set数组与placePieces数组进行比较。
我已经为每个placePieces数组创建了循环,以循环遍历winPattern 2d数组,但是由于它无法将每个数组识别为一个集合,而只是迭代各个值,因此无法按预期工作。
const winPattern = [
//horizontal
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
//vertical
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
//diagonal
[0, 4, 8],
[2, 4, 6]
];
//positions that o or x would be in tictactoe
const placePieces = [0, 1, 2, 4, 8];
let count = 0;
nextPiece:
for (let i = 0; i < placePieces.length; i++) {
for (let j = 0; j < winPattern.length; j++) {
for (let n = 0; n < winPattern[0].length; n++) {
if (placePieces[i] === winPattern[j][n]) {
//Prints out the matches and mismatches
console.log(`It matches: Piece: ${placePieces[i]} //\\ Pattern: ${winPattern[j][n]}`);
continue nextPiece;
} else {
console.log(`It doesn't match: Piece: ${placePieces[i]} //\\Pattern: ${winPattern[j][n]}`);
}
}
}
}
我期望placePieces数组将值与winPattern 2d数组中的每个SET数组进行比较。
答案 0 :(得分:1)
此代码应该可以查看用户当前数组是否与答案数组中的任何内容匹配-
var winPattern = [
//horizontal
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
//vertical
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
//diagonal
[0, 4, 8],
[2, 4, 6]
];
//positions that o or x would be in tictactoe
var placePieces = [0, 1, 2, 4, 8, ];
var count = 0;
function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
function checkMatch(arr){
for(var i = 0; i < winPattern.length; i++){
for(var j = 0; j < arr.length - 2; j++){
for(var k = j + 1; k < arr.length - 1; k++){
for(var l = k + 1; l < arr.length; l++){
var possibleAnswer = [arr[j], arr[k], arr[l]];
if(arraysEqual(possibleAnswer, winPattern[i])) return true;
}
}
}
}
return false;
}
这是假设placePieces已排序,因为看起来像您的示例中那样。希望这会有所帮助!