Tic Tac Toe, Help/Determine Winner

前端 未结 4 904
离开以前
离开以前 2021-01-28 23:42

I\'m creating a TicTacToe class that contains a 3 by 3 rectangular array of integers & is played by 2 human players. \"1\" is used for the first player\'s move & \"2\" i

4条回答
  •  既然无缘
    2021-01-29 00:03

    As Iiya has said, you're going to have to through through all the win cases. There's many ways to do that but the very gist of it in code would be

    private bool checkWinner(int player)
    {
        // check rows
        if (board[0, 0] == player && board[0, 1] == player && board[0, 2] == player) { return true; }
        if (board[1, 0] == player && board[1, 1] == player && board[1, 2] == player) { return true; }
        if (board[2, 0] == player && board[2, 1] == player && board[2, 2] == player) { return true; }
    
        // check columns
        if (board[0, 0] == player && board[1, 0] == player && board[2, 0] == player) { return true; }
        if (board[0, 1] == player && board[1, 1] == player && board[2, 1] == player) { return true; }
        if (board[0, 2] == player && board[1, 2] == player && board[2, 2] == player) { return true; }
    
        // check diags
        if (board[0, 0] == player && board[1, 1] == player && board[2, 2] == player) { return true; }
        if (board[0, 2] == player && board[1, 1] == player && board[2, 0] == player) { return true; }
    
        return false;
    }
    

    You can optimise this however which way you'd like (using for loops or matrices). Note the checkWinner() function requires a player input.

提交回复
热议问题