我正在制作Tic Tac Toe游戏,我遇到了问题。我注意到可获胜的情况是当有3个数字相等时(例如,“ 0,1,2”(1-0 = 1,2-1 = 1)或“ 0,4,8”(4- 0 = 4、8-4 = 4)或“ 1,4,7”(4-1 = 3、7-4 = 3),如果我从“ 0”开始计数)。数字是框的坐标,范围是0到8。
不知道如何检查是否有这样的数字。
((void(*)()) (&pointerToTheStruct + sizeof(int)))();
我要将每个x坐标粘贴到数组“ x”(x.push [i]),然后将o坐标粘贴到“ o”数组(o.push [i]),但是我不知道如何进行searc数组中相同的数字。
答案 0 :(得分:0)
类似的事情会起作用。
function didWin(arr) {
let len = arr.length; // I like checking length once because it's O(n). Probably won't matter for your game, though.
if (len < 3)
return false; // No win if less than 3 moves
var firstDiff = arr[1] - arr[0];
for (var i = 1; i < len - 1; ++i) { // We don't check the first (already done) or the last (no arr[len] element)
if (arr[i+1] - arr[i] != firstDiff)
return false; // We know we are done as soon as the difference is not equal
}
return true; // We have now checked that all differences are equal
}
答案 1 :(得分:0)
您可以创建两个函数,一个函数生成“差异”数组,另一个函数检查所有这些数字是否相同。参见下面的代码:
const array = [1, 4, 7];
// Function to get differences
function getDiffs(array) {
let diffs = [];
for(let i=0; i<array.length; i++) {
if(i > 0) {
diffs.push(array[i] - array[i-1]);
}
}
return diffs;
}
// Function to compare those numbers to see if they are the same
function checkSameValue(diffs) {
let item = diffs[0];
for(let i=0; i< diffs.length; i++) {
if(diffs[i] !== item) {
return false;
}
}
return true;
}
希望有帮助!