我已经获得了一个tic tac toe游戏的代码。我制作了代码来检查垂直是否会赢,并试图检查对角线。我能够检查主对角线,但似乎无法确定如何检查辅助对角线。我认为我的代码可以工作,但事实并非如此。我遇到的问题从第172行开始
var array_nums = Array.apply(null, Array(50)).map(function() {
return Math.floor(Math.random() * 50);
}).reduce(function (acc, curr) {
if (curr >= 10 && curr <= 19) {
acc[curr] = (acc[curr] || 0) + 1;
acc["all"]++;
}
return acc;
}, {all:0});
document.getElementById("results").innerHTML = JSON.stringify(array_nums);
答案 0 :(得分:1)
您的代码逻辑错误。如果主对角线上的单元格不等于mark
,则只检查辅助对角线。
您需要两个单独的变量来跟踪每条对角线是否有胜利。您的代码应如下所示:
int match_prime = 1, match_second = 1;
for(col = 0;col < BOARD_SIZE;++col){
match_prime = board[col][col] == mark;
match_second = board[BOARD_SIZE - col - 1][col] == mark;
}
won = match_prime || match_second;
答案 1 :(得分:0)
方法1
对角元素索引的硬编码。
int hasWonDiagonal(char board[BOARD_SIZE][BOARD_SIZE], char mark) {
int won = 0;
int match = 0;
if ( ( board[0][0] == mark &&
board[1][1] == mark &&
board[2][2] == mark ) &&
( board[0][2] == mark &&
board[1][1] == mark &&
board[2][0] == mark ) )
{
match = 1;
}
won = match;
return won; // Stub -- make this return the correct value
}
方法2
使用for
循环并迭代索引。
int hasWonDiagonal(char board[BOARD_SIZE][BOARD_SIZE], char mark) {
int match = 1;
int won = 0;
int row = 0;
// Check the first diagonal.
for (row = 0; row < BOARD_SIZE && !won; row++) {
if(board[row][row] != mark) {
match=0;
}
}
// If the first diagonal check already produces a match,
// there is no need to check the second diagonal.
if ( match != 1 )
{
int col = BOARD_SIZE-1;
for (row = 0; row < BOARD_SIZE && !won; row++, col--) {
if(board[row][col] != mark){
match=0;
}
}
}
won = match;
return won; // Stub -- make this return the correct value
}
答案 2 :(得分:0)
这些功能可以采用以下方式
//
// Determines if the 'mark' completely fills a row
// returns 1 if yes, 0 if no
//
int hasWonHorizontal( char board[BOARD_SIZE][BOARD_SIZE], char mark )
{
int won = 0; // boolean (0/1).
for ( int row = 0; row < BOARD_SIZE && !won; row++ )
{
int col = 0;
while ( col < BOARD_SIZE && board[row][col] == mark ) ++col
won = col == BOARD_SIZE;
}
return won;
}
//
// Determines if the 'mark' completely fills a column
// returns 1 if yes, 0 if no
//
int hasWonVertical( char board[BOARD_SIZE][BOARD_SIZE], char mark )
{
int won = 0;
for ( int col = 0; col < BOARD_SIZE && !won; col++ )
{
int row = 0;
while ( row < BOARD_SIZE && board[row][col] == mark ) ++row;
won = row == BOARD_SIZE;
}
return won; // Stub -- make this return the correct value
}
//
// Determines if the 'mark' completely fills a diagonal
// returns 1 if yes, 0 if no
//
int hasWonDiagonal(char board[BOARD_SIZE][BOARD_SIZE], char mark)
{
int won = 0;
int i = 0;
while ( i < BOARD_SIZE && board[i][i ] == mark ) ++i;
won = i == BOARD_SIZE;
if ( !won )
{
i = 0;
while ( i < BOARD_SIZE && board[i][BOARD_SIZE - i - 1 ] == mark ) ++i;
won = i == BOARD_SIZE;
}
return won; // Stub -- make this return the correct value
}