【问题标题】:How can I prevent players from overwriting one another in tic tac toe?如何防止玩家在井字游戏中相互覆盖?
【发布时间】:2021-11-20 16:07:23
【问题描述】:

我尝试用 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 方法中。但这并没有解决我的问题。

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

【问题讨论】:

    标签: c# tic-tac-toe


    【解决方案1】:

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

    例如,这里有一个较短的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!");
        }
    }
    

    您能解释一下为什么要按照您的方式设置索引吗?

    当然!这里是板子的布局,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。因此,我们从列值中减去 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
    

    但是我怎么会想到这样的事情呢?我会 从来没有想过。

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

    【讨论】:

    • 哦,这样更有效。不会想到的。谢谢。
    • 你能解释一下为什么你设置索引的方式吗?我真的不明白对不起。我认为我的问题是,当我看到一个问题时,除非我查看不同的解决方案,否则我真的不知道如何解决它超过一定程度的复杂性......有什么建议吗?
    • 就像,我知道存在索引来计算玩家输入(行、列)指示的位置。但是我怎么会想到这样的事情呢?我永远不会想到这一点。
    • 在编辑后的答案底部查看新的 cmets 和解释。
    • 谢谢,我还可以和应该在程序中缩短什么?
    【解决方案2】:

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

    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;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多