Connect Four Console App Lagging при проверке хода - PullRequest
0 голосов
/ 04 января 2019

Работа на C # connect четыре консольных приложения. У меня есть следующий код, который должен побудить пользователя ввести строку для добавления токена, отобразить, куда он упал, проверить, есть ли в строке 4 по горизонтали, вертикали и диагонали.

using System;

namespace connectfour
{
    class Program
    {
        public static int[][] board = new int[6][];

        public struct playerInfo
        {
            public string playerName;
            public char playerID;
        }

        //Player 1 by default
        static int playerTurn = 1;

        static void Main(string[] args)
        {
            playerInfo playerOne = new playerInfo();
            playerInfo playerTwo = new playerInfo();

            Console.WriteLine("Welcome to Connect Four!");
            Console.WriteLine();
            Console.WriteLine("Player One, please enter your name: ");
            playerOne.playerName = Console.ReadLine();
            playerOne.playerID = 'X';
            Console.WriteLine();
            Console.WriteLine("Player Two, please enter your name: ");
            playerTwo.playerName = Console.ReadLine();
            playerTwo.playerID = 'O';

            int win = 0;

            CreateBoard();

            while (win == 0)
            {
                if (playerTurn == 1)
                {
                    Console.WriteLine();
                    Console.WriteLine(playerOne.playerName + " please select a row: ");
                    if (int.TryParse(Console.ReadLine(), out var userInput))
                    {
                        if (PlayerChoice(userInput, playerOne.playerID))
                        {
                            WinCondition(userInput, playerOne.playerID);
                            ChangeTurn();
                        }
                    }
                }
                else if (playerTurn == 2)
                {
                    Console.WriteLine();
                    Console.WriteLine(playerTwo.playerName + " please select a row: ");
                    if (int.TryParse(Console.ReadLine(), out var userInput))
                    {
                        if (PlayerChoice(userInput, playerTwo.playerID))
                        {
                            WinCondition(userInput, playerTwo.playerID);
                            ChangeTurn();
                        }
                    }
                }
            }
            if(win == 1)
            {
                EndGame(playerOne, playerTwo);
            }
        }

        static void CreateBoard()
        {
            for (int row = 0; row < board.Length; row++)
            {
                for (int column = 0; column <= board.Length; column++)
                {
                    board[row] = new int[7];
                    Console.Write(((char)board[row][column]) + " . ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();
            Console.WriteLine();
        }

        static bool PlayerChoice(int userInput, char playerID)
        {
            var isValidMove = false;

            if (userInput <= board[0].Length)
            {
                var row = GetRowForMove(--userInput);

                if (row != -1)
                {
                    board[row][userInput] = playerID;
                    DisplayBoard();
                    isValidMove = true;
                }
                else
                {
                    Console.WriteLine("You can't go there!");
                }
            }
            else
            {
                Console.WriteLine("Please enter a valid row.");
            }
            return isValidMove;
        }

        static int GetRowForMove(int colChoice)
        {
            for (int i = board.Length - 1; i >= 0; i--)
            {
                if (board[i][colChoice] == 0)
                {
                    return i;
                }
            }
            return -1;
        }

        static void DisplayBoard()
        {
            for (int row = 0; row < board.Length; row++)
            {
                for (int column = 0; column < board[row].Length; column++)
                {
                    Console.Write(((char)board[row][column]) + " . ");
                }
                Console.WriteLine();
            }
        }
        static void ChangeTurn()
        {
            if (playerTurn == 1)
            {
                playerTurn = 2;
            }
            else if (playerTurn == 2)
            {
                playerTurn = 1;
            }
        }

        static void WinCondition(int userInput, char playerID)
        {
            int win;

            win = 0;

            while (win == 0)
            {
                CheckHorizontal(userInput);
                CheckVertical(userInput);
                CheckDiagonalLeft(userInput);
                CheckDiagonalRight(userInput);
            }
        }

        //If player has 4 in a row horizontally
        static int CheckHorizontal(int userInput)
        {
            int XO = userInput;
            int win = 0;

            for (int row = board.Length - 1; row <= 5; row--)
            {
                for(int col = board[0].Length - 1; col <= 3; col--)
                {
                    if (XO != 0 &&
                        XO == board[XO][col - 1] &&
                        XO == board[XO][col - 2] &&
                        XO == board[XO][col - 3])
                    {
                        win = 1;
                    }
                }
             }
             return win;
            }

        //If player has 4 in a row vertically
        static int CheckVertical(int userInput)
        {
            int XO = userInput;
            int win = 0;

            for (int row = board.Length - 1; row <= 2; row--)
            {
                for (int col = board[0].Length - 1; col <= 3; col--)
                {
                    if (XO != 0 &&
                        XO == board[row - 1][XO] &&
                        XO == board[row - 2][XO] &&
                        XO == board[row - 3][XO])
                    {
                        win = 1;
                    }
                }
            }
            return win;
        }

        //If player has 4 in a row top-right to bottom-left
        static int CheckDiagonalRight(int userInput)
        {
            int XO = userInput;
            int win = 0;

            for (int row = board.Length - 1; row <= 2; row--)
            {
                for (int col = board[0].Length - 1; col <= 3; col--)
                {
                    if (XO != 0 &&
                        XO == board[XO + 1][XO + 1] &&
                        XO == board[XO + 2][XO + 2] &&
                        XO == board[XO + 3][XO + 3])
                    {
                        win = 1;
                    }
                }
            }
            return win;
        }

        //If player has 4 in a row top-right to bottom-left
        static int CheckDiagonalLeft(int userInput)
        {
            int XO = userInput;
            int win = 0;

            for (int row = board.Length - 1; row <= 5; row--)
            {
                for (int col = board[0].Length - 1; col <= 3; col--)
                {
                    if (XO != 0 &&
                        XO == board[XO - 1][XO + 1] &&
                        XO == board[XO - 2][XO + 2] &&
                        XO == board[XO - 3][XO + 3])
                    {
                        win = 1;
                    }
                }
            }
            return win;
        }

        static void EndGame(playerInfo playerOne, playerInfo playerTwo)
        {
            if(playerTurn == 1)
            {
                Console.WriteLine("Connect Four, " + playerOne + " you win!");
            }
            else if(playerTurn == 2)
            {
                Console.WriteLine("Connect Four, " + playerTwo + " you win!");
            }

        }
    }
}

Проблема, с которой я сталкиваюсь, заключается в том, что консоль отстает от методов CheckHorizont () и CheckDiagonalLeft () при их обходе во время отладки ... до такой степени, что она даже не переходит к следующему игроку для запроса за ход.

Кроме того, я пытаюсь сделать так, чтобы проверки выполнялись из текущего сброшенного токена, а не для проверки всей доски каждый раз ... Я не уверен, правильно ли это выражают мои операторы if, если это так.

Может, кто-нибудь подскажет, что заставляет консоль зависать и как я могу точно написать эти операторы if?

Спасибо!

1 Ответ

0 голосов
/ 04 января 2019

Может быть, есть еще проблема, но один ниже вызывает бесконечный цикл:

while (win == 0)
{
    CheckHorizontal(userInput);
    CheckVertical(userInput);
    CheckDiagonalLeft(userInput);
    CheckDiagonalRight(userInput);
}

ваш "выигрыш" всегда равен 0, и цикл никогда не заканчивается.

Ваш метод WinCondition должен возвращать логическое значение и выглядеть примерно так:

    static bool WinCondition(int userInput)
    {
        return CheckHorizontal(userInput) == 1 ||
            CheckVertical(userInput) == 1 ||
            CheckDiagonalLeft(userInput) == 1 ||
            CheckDiagonalRight(userInput) == 1 ||;
//you can modify Check... methods to return bool as well, it would be more readable
        }
    }

А в основном методе должно быть что-то вроде:

if(WinCondition(userInput))
{
    win = 1;
}
else
{
    ChangeTurn();
}
...