如何防止玩家在井字游戏中互相覆盖?

How can I prevent players from overwriting one another in tic tac toe?

我尝试用 C# 编写一个井字游戏(在教程的帮助下)。总的来说它似乎工作正常(虽然代码量似乎非常多,对此感到抱歉)但似乎有一个问题:比如说,玩家 1 决定第 1 行,第 1 列,然后玩家 2 做同样的事情,然后玩家2 覆盖播放器 1。 到目前为止,这是代码:

namespace TicTacToe
{
    class Program
    {
    static int turns = 1;
    static char[] board =
    {
        ' ',' ',' ',' ',' ',' ',' ',' ',' '
    };
    static char playerSignature = 'X'; 
    private static void Introduction()
    {
        Console.WriteLine("This is a simple TicTacToe game. Enter y if you have played before and n if you are new to this.");
        string input1 = Console.ReadLine();
        Console.Clear();
        if (input1 == "n")
        {
            Console.WriteLine("TicTacToeRules:");
            Console.WriteLine("1. The game is played on a grid that's 3 squares by 3 squares.");
            Console.WriteLine("2. You are X, your friend is O. Players take turns putting their marks in empty squares.");
            Console.WriteLine("3. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.");
            Console.WriteLine("4. When all 9 squares are full, the game is over.");
            Console.WriteLine("If you have read the rules, press any key to continue.");
            Console.ReadKey();
            Console.Clear();
            DrawBoard(board);
        }
        else
        {
            Console.WriteLine("Alright, let's get started, you are X, your friend is O.");
            DrawBoard(board);
        }
    }
    private static void PlayAgain()
    {
        Console.WriteLine("Play again? y/n");
        string playagain = Console.ReadLine();
        switch (playagain)
        {
            case "n":
                Console.WriteLine("Thanks for playing!");
                Console.Clear();
                break;
            case "y":
                Console.Clear();
                ResetBoard();
                break;
        }
    }
    private static void DrawBoard(char[] board)
    {

        string row = "| {0} | {1} | {2} |";
        string sep = "|___|___|___|";
        Console.WriteLine(" ___ ___ ___ ");
        Console.WriteLine(row, board[0], board[1], board[2]);
        Console.WriteLine(sep);
        Console.WriteLine(row, board[3], board[4], board[5]);
        Console.WriteLine(sep);
        Console.WriteLine(row, board[6], board[7], board[8]);
        Console.WriteLine(sep);
    }
    private static void ResetBoard()
    {
        char[] newBoard =
        {
        ' ',' ',' ',' ',' ',' ',' ',' ',' '
        };
        board = newBoard;
        DrawBoard(board);
        turns = 0;
    }
    private static void Draw()
    {
        Console.WriteLine("It's a draw!\n" +
                            "Press any key to play again.");
        Console.ReadKey();
        ResetBoard();
        //DrawBoard(board);
    }
    public static void Main()
    {
        Introduction();
        while(true)
        {
            bool isrow = false;
            bool iscol = false;
            int row = 0;
            int col = 0;
                while (!isrow)
                {
                    Console.WriteLine("Choose a row (1-3): ");
                    try
                    {
                        row = Convert.ToInt32(Console.ReadLine());
                    }
                    catch
                    {

                        Console.WriteLine("Please enter a number between 1 and 3.");
                    }
                    if (row == 1 || row == 2 || row == 3)
                    {
                        isrow = true;
                    }
                    else
                    {
                        Console.WriteLine("\nInvalid row!");
                    }
                }
                while (!iscol)
                {
                    Console.WriteLine("Choose a column (1-3): ");
                    try
                    {
                        col = Convert.ToInt32(Console.ReadLine());
                    }
                    catch
                    {
                        Console.WriteLine("Please enter a number between 1 and 3.");
                    }
                    if (col == 1 || col == 2 || col == 3)
                    {
                        iscol = true;
                    }
                    else
                    {
                        Console.WriteLine("\nInvalid column!");
                    }
                }
            int[] input = { row, col };
            int player = 2;
            if (player == 2)
            {
                player = 1;
                XorO(player, input);
            }
            else
            {
                player = 2;
                XorO(player, input);
            }
            DrawBoard(board);
            turns++;
            CheckForDiagonal();
            CheckForVertical();
            CheckForHorizontal();
            if (turns == 10 && (board[0] == playerSignature && board[1] == playerSignature && board[2] == playerSignature && board[3] == playerSignature &&
                board[4] == playerSignature && board[5] == playerSignature && board[6] == playerSignature && board[7] == playerSignature && board[8] == playerSignature))
            {
                Draw();
            }
        }
    }
    private static void CheckForVertical()
    {
        char[] PlayerSignature = { 'O', 'X' };
        foreach (char Signature in PlayerSignature)
        {
            if (board[0] == playerSignature && board[3] == playerSignature && board[6] == playerSignature ||
            board[1] == playerSignature && board[4] == playerSignature && board[7] == playerSignature ||
            board[2] == playerSignature && board[5] == playerSignature && board[8] == playerSignature)
            {
                if (playerSignature == 'X')
                {
                    Console.WriteLine("Congratulations Player 1, that's a vertical win!\n" +
                        "Play again (y/n)?");
                    string playagain = Console.ReadLine();
                    if (playagain == "y")
                    {
                        Console.Clear();
                        ResetBoard();
                        turns = 0;
                    }
                    else
                    {
                        Console.Clear();
                    }

                }
                else
                {
                    Console.WriteLine("Congratulations Player 2, that's a vertical win!\n" +
                        "Play again (y/n)?");
                    string playagain = Console.ReadLine();
                    if (playagain == "y")
                    {
                        Console.Clear();
                        ResetBoard();
                        turns = 0;
                    }
                    else
                    {
                        Console.Clear();
                    }
                }
            }
        }
    }
    private static void CheckForHorizontal()
    {
        char[] PlayerSignature = { 'O', 'X' };
        foreach (char Signature in PlayerSignature)
        {
            if (board[0] == playerSignature && board[1] == playerSignature && board[2] == playerSignature ||
                board[3] == playerSignature && board[4] == playerSignature && board[5] == playerSignature ||
                board[6] == playerSignature && board[7] == playerSignature && board[8] == playerSignature)
            {
                if (playerSignature == 'X')
                {
                    Console.WriteLine("Congratulations Player 1, that's a horizontal win!\n" +
                        "Play again (y/n)?");
                    string playagain = Console.ReadLine();
                    if (playagain == "y")
                    {
                        Console.Clear();
                        ResetBoard();
                        turns = 0;
                    }
                    else
                    {
                        Console.Clear();
                    }

                }
                else
                {
                    Console.WriteLine("Congratulations Player 2, that's a horizontal win!\n" +
                        "Play again (y/n)?");
                    string playagain = Console.ReadLine();
                    if (playagain == "y")
                    {
                        Console.Clear();
                        ResetBoard();
                        turns = 0;
                    }
                    else
                    {
                        Console.Clear();
                    }
                }
            }
        }
    }
    private static void CheckForDiagonal()
    {
        char[] PlayerSignature = { 'O', 'X' };
        foreach (char Signature in PlayerSignature)
        {
            if (board[6] == playerSignature && board[4] == playerSignature && board[2] == playerSignature ||
            board[0] == playerSignature && board[4] == playerSignature && board[8] == playerSignature)
            {
                if (playerSignature == 'X')
                {
                    Console.WriteLine("Congratulations Player 1, that's a diagonal win!\n" +
                        "Play again (y/n)?");
                    string playagain = Console.ReadLine();
                    if (playagain == "y")
                    {
                        Console.Clear();
                        ResetBoard();
                        turns = 0;
                    }
                    else
                    {
                        Console.Clear();
                    }

                }
                else
                {
                    Console.WriteLine("Congratulations Player 2, that's a diagonal win!\n" +
                        "Play again (y/n)?");
                    string playagain = Console.ReadLine();
                    if (playagain == "y")
                    {
                        Console.Clear();
                        ResetBoard();
                        turns = 0;
                    }
                    else
                    {
                        Console.Clear();
                    }
                }
            }
        }
        
    }
    private static void XorO(int player, int[] input)
    {
        if (player == 1)
        {
            playerSignature = 'X';
        }
        else if (player == 2)
        {
            playerSignature = 'O';
        }

        if (input[0] == 1 && input[1] == 1)
        {
            board[0] = playerSignature;
        }
        else if (input[0] == 1 && input[1] == 2)
        {
            board[1] = playerSignature;
        }
        else if (input[0] == 1 && input[1] == 3)
        {
            board[2] = playerSignature;
        }
        else if (input[0] == 2 && input[1] == 1)
        {
            board[3] = playerSignature;
        }
        else if (input[0] == 2 && input[1] == 2)
        {
            board[4] = playerSignature;
        }
        else if (input[0] == 2 && input[1] == 3)
        {
            board[5] = playerSignature;
        }
        else if (input[0] == 3 && input[1] == 1)
        {
            board[6] = playerSignature;
        }
        else if (input[0] == 3 && input[1] == 2)
        {
            board[7] = playerSignature;
        }
        else if (input[0] == 3 && input[1] == 3)
        {
            board[8] = playerSignature;
        }
    }
}

}

我试过添加这样的东西:if(input[0] == 1 && input[1] == 1 && (board[0] != 'X' && board[0] != 'O') 在 XorO 方法中。但这并没有解决我的问题。

有人可能对我如何解决这个问题有一些建议吗?

您在其中一些方法中做的工作太多了...

例如,这里有一个较短的 XorO() 方法,它还可以确保在分配给玩家之前该位置是空白的:

private static void XorO(int player, int[] input)
{
    playerSignature = (player == 1) ? 'X' : 'O';
    int index = ((input[0] - 1) * 3) + (input[1] - 1);
    if (board[index] == ' ') {
        board[index] = playerSignature;
    }
    else {
        // ... output an error message? ...
        Console.WriteLine("That spot is already taken!");
    }
}

Could you maybe explain why you set index the way you did?

好的!下面是棋盘的布局,3行3列,每个位置对应的Index值:

  1 2 3
1 0 1 2
2 3 4 5
3 6 7 8

请注意,因为有 3 列,当我们在同一列中从一行向下移动到下一行时,索引的值会增加 3。另请注意,每行的第 1 列中的起始值为0、3、6,它们都是3的倍数。所以要把你的行值从1、2、3转换成0、3、6,我们先把行值减1,然后乘以3。

接下来,当您向右移动时,每一列只会递增 1。因此,我们从列值中减去一个并将其添加到计算的起始行值。这会将 (row, col) 映射到索引 0 到 8,此处视为一维数组:

1,1 | 1,2 | 1,3 | 2,1 | 2,2 | 2,3 | 3,1 | 3,2 | 3,3
 0  |  1  |  2  |  3  |  4  |  5  |  6  |  7  |  8

But how was am I supposed to think of something like that? I would never have thought of that.

在称为 compact layout 的一维数组中表示二维结构是一种相当常见的设置。将 row/column 转换为等效索引值(反之亦然)所涉及的数学只是所有程序员在某个时候学习的东西。

这里有很多重构,仔细看:

class Program
{
    
    static int turns;
    static char[] board;
    static bool playerOne;

    public static void Main(string[] args)
    {
        Introduction();

        bool playAgain = true;
        while (playAgain)
        {
            ResetBoard();                
            bool gameOver = false;
            while (!gameOver)
            {
                DrawBoard(board);
                int row = getNumber(true);
                int col = getNumber(false);
                if (XorO(row, col)) {
                    turns++; // valid move was made
                    String msg = "";
                    String playerNumber = playerOne ? "1" : "2";
                    if (CheckForDiagonal())
                    {
                        gameOver = true;
                        msg = "Congratulations Player " + playerNumber + ", that's a diagonal win!";
                    }
                    else if (CheckForVertical())
                    {
                        gameOver = true;
                        msg = "Congratulations Player " + playerNumber + ", that's a vertical win!";
                    }
                    else if (CheckForHorizontal())
                    {
                        gameOver = true;
                        msg = "Congratulations Player " + playerNumber + ", that's a horizontal win!";
                    }
                    else if (turns == 9)
                    {
                        gameOver = true;
                        msg = "It's a draw!";
                    }
                    else
                    {
                        playerOne = !playerOne;
                    }

                    if (gameOver)
                    {
                        DrawBoard(board); // show last move
                        Console.WriteLine(msg);
                    }
                }                    
            }

            Console.WriteLine("Play again (y/n)?");
            string response = Console.ReadLine().ToLower();
            playAgain = (response == "y");
        }
    }

    private static void ResetBoard()
    {
        turns = 0;
        playerOne = true;
        board = new char[] {
            ' ',' ',' ',' ',' ',' ',' ',' ',' '
        };
    }

    private static void Introduction()
    {
        Console.WriteLine("This is a simple TicTacToe game.\nEnter y if you have played before and n if you are new to this.");
        string input1 = Console.ReadLine().ToLower();
        Console.Clear();
        if (input1 == "n")
        {
            Console.WriteLine("TicTacToeRules:");
            Console.WriteLine("1. The game is played on a grid that's 3 squares by 3 squares.");
            Console.WriteLine("2. You are X, your friend is O. Players take turns putting their marks in empty squares.");
            Console.WriteLine("3. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.");
            Console.WriteLine("4. When all 9 squares are full, the game is over.");
            Console.WriteLine("If you have read the rules, press any key to continue.");
            Console.ReadKey();
            Console.Clear();               
        }
        else
        {
            Console.WriteLine("Alright, let's get started, you are X, your friend is O.");
        }
    }

    private static void DrawBoard(char[] board)
    {
        Console.WriteLine(" ___ ___ ___ ");
        for(int r=1; r<=3;r++)
        {
            Console.Write("|");
            for(int c=1; c<=3; c++)
            {
                Console.Write(" {0} |", board[(r - 1) * 3 + (c - 1)]);
            }
            Console.WriteLine();
            Console.WriteLine("|___|___|___|");
        }            
    }

    private static int getNumber(bool row)
    {
        int value = -1;
        string description = row ? "row" : "column";
        bool isValid = false;
        while (!isValid)
        {
            Console.Write("Player '" + (playerOne ? "X" : "O")  + "', choose a " + description + " (1-3): ");
            if (int.TryParse(Console.ReadLine(), out value))
            {
                if (value >= 1 && value <= 3)
                {
                    isValid = true;
                }
                else
                {
                    Console.WriteLine("Please enter a number between 1 and 3.");
                }
            }
            else
            {
                Console.WriteLine("\nInvalid " + description + "!");
            }
        }
        return value;
    }

    private static bool XorO(int row, int col)
    {
        int index = ((row - 1) * 3) + (col - 1);
        if (board[index] == ' ')
        {
            board[index] = playerOne ? 'X' : 'O';
            return true;
        }
        else
        {
            Console.WriteLine("That spot is already taken!");
            return false;
        }
    }

    private static bool CheckForDiagonal()
    {
        return ((board[6] != ' ' && board[4] == board[6] && board[2] == board[6]) ||
            (board[0] != ' ' && board[4] == board[0] && board[8] == board[0]));
    }

    private static bool CheckForVertical()
    {
        for(int c=0; c<=2; c++)
        {
            if (board[c] != ' ' && board[c+3] == board[c] && board[c+6] == board[c])
            {
                return true;
            }
        }
        return false;
    }

    private static bool CheckForHorizontal()
    {
        for (int r=0; r<=6; r=r+3)
        {
            if (board[r] != ' ' && board[r + 1] == board[r] && board[r + 2] == board[r])
            {
                return true;
            }
        }
        return false;
    }

}