例如,我需要在一个二维数组中搜索一个正负梯度值。
正梯度:左下〉中间〉右上
负梯度:左上〉中间〉右下
[
['x', 'x', 'o'],
[null, null, 'o'],
['x', 'x', null]
]
我有两个函数。首先在for循环中找到值,当找到值时,这两个函数都运行以搜索迷宫的正梯度和负梯度,如果找到获胜的组合,则返回true。
scanfornegativegradientcombinations工作,scanForPositiveGradientCombinations不工作,并以typeError结束。我认为问题可能是在减少rowIndex时,我正在将游戏推出界限,但我不确定。
const isDiagonalWinner = (rowCellValues, winCountCondition, player) => {
for(let rowIndex = 0; rowIndex < rowCellValues.length; rowIndex++){
for(let columnIndex = 0; columnIndex < rowCellValues[rowIndex].length; columnIndex++){
const cellValue = rowCellValues[rowIndex][columnIndex];
if(cellValue === player.symbol) {
console.log('initiating player scan for ', player.symbol, 'at', [rowIndex, columnIndex]);
if(scanForNegativeGradientCombinations(columnIndex, rowIndex, rowCellValues, player.symbol, winCountCondition)) {
return true
}
if(scanForPositiveGradientCombinations(columnIndex, rowIndex, rowCellValues, player.symbol, winCountCondition)) {
return true
}
}
}
}
return null;
};
以上是将调用以下2个函数的函数。
const scanForNegativeGradientCombinations= (columnIndex, rowIndex, rowCellValues, playerSymbol, winCountCondition) => {
let counter = 0;
while(rowIndex < rowCellValues.length && columnIndex < rowCellValues[rowIndex].length){
if(rowCellValues[rowIndex][columnIndex] === playerSymbol){
counter++;
}
if(counter >= winCountCondition){
return true;
}
rowIndex++;
columnIndex++;
}
return false;
}
const scanForPositiveGradientCombinations= (columnIndex, rowIndex, rowCellValues, playerSymbol, winCountCondition) => {
let counter = 0;
while(rowIndex < rowCellValues.length && columnIndex < rowCellValues[rowIndex].length){
if(rowCellValues[rowIndex][columnIndex] === playerSymbol){
counter++;
}
if(counter >= winCountCondition){
return true;
}
rowIndex--;
columnIndex++;
}
return false;
}
1条答案
按热度按时间wbrvyc0a1#