c++ - Tic-Tac-Toe Program -
i'm trying create tic-tac-toe program determine if given playing board won "x" "o" or tie.
obviously know games won who, how can program check that?
int check(int board[3][3]) { //i've tried putting code here, nothing successful. return 0; } int main() { // three-dimensional array, 3 games of two-dimensional // boards; concern two-dimensional boards int games[3][3][3] = { { { -1, 0, 1 }, //o_x { 0, 1, -1 }, //_xo { 1, -1, 0 } //xox }, { { 0, 1, 1 }, //_xx { -1, -1, -1 }, //ooo { 1, 1, 0 } //xx_ }, { { 1, 1, -1 }, //xxo { -1, -1, 1 }, //oox { 1, 1, -1 } //xxo } }; (int game = 0; game < 3; game++) { if (check(games[game]) == 1) { cout << "player x wins game " << game + 1 << endl; } else if (check(games[game]) == -1) { cout << "player o wins game " << game + 1 << endl; } else { cout << "game " << game + 1 << " cat game" << endl; } } return 0; }
this should work:
int check(int board[3][3]) { int winner = 0; // check line for( int i=0; i<3; ++i ) { if( board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != 0) winner = board[i][0]; } // check column for( int i=0; i<3; ++i ) { if( board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != 0 ) winner = board[0][i]; } // check diagonal if( board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != 0) winner = board[1][1]; if( board[2][1] == board[1][1] && board[1][1] == board[0][2] && board[1][1] != 0) winner = board[1][1]; return winner; }
Comments
Post a Comment