Проблемы с преобразованием массивов в методы - PullRequest
0 голосов
/ 25 марта 2019

Я пытаюсь взять кусок кода, который отображает крестики-нолики и преобразовать его в методы. Это оказывается чрезвычайно трудным, и хотя я чувствую, что я следую правилам, я ничего не могу заставить работать. Мне нужна помощь в выяснении того, как заставить код работать вместе (например, установите флажок win или tie из пользовательского ввода вверху.

static void()
      {
        int computerSquare = 0;
        int userSquare = 0;
        bool playerTurn = true;
        int whoFirst = 0;
        string winCheck = null;
        string[,] theBoard = new string[3, 3]
        {   { " ", " ", " "},
                { " ", " ", " "},
                { " ", " ", " "}   };
        int placesFilled = 0;


        Random myRandomGenerator = new Random();  //Initializing the random generator

        //Explain the game to the player
        Console.WriteLine("Welcome to Tic-Tac-Toe.  You will be X and the computer will be O.\n");
        Console.WriteLine("On your turn please indicate which square you want to select by entering" +
            " the number as shown below.\n");
        Console.WriteLine(" 1 | 2 | 3");
        Console.WriteLine("---|---|---");
        Console.WriteLine(" 4 | 5 | 6");
        Console.WriteLine("---|---|---");
        Console.WriteLine(" 7 | 8 | 9");
        Console.WriteLine("\nPlease enter any key when you are ready to begin playing. ");
        Console.ReadKey();

        //figure who goes first here, set firstTurn appropriately
        whoFirst = myRandomGenerator.Next(0, 2);
        if (whoFirst == 0)
        {
            playerTurn = false;
            Console.WriteLine("The computer will go first");
            Console.ReadKey();
        }

        //Display the blank board
        Console.Clear();

        Console.WriteLine($" {theBoard[0, 0]} | {theBoard[0, 1]} | {theBoard[0, 2]}");
        Console.WriteLine("---|---|---");
        Console.WriteLine($" {theBoard[1, 0]} | {theBoard[1, 1]} | {theBoard[1, 2]}");
        Console.WriteLine("---|---|---");
        Console.WriteLine($" {theBoard[2, 0]} | {theBoard[2, 1]} | {theBoard[2, 2]}");

    }

    static void CheckForSquare()
    {
        int computerSquare = 0;
        int userSquare = 0;
        bool playerTurn = true;
        int whoFirst = 0;
        string winCheck = null;
        string[,] theBoard = new string[3, 3]
        {   { " ", " ", " "},
                { " ", " ", " "},
                { " ", " ", " "}   };
        int placesFilled = 0; 

        if (playerTurn)
        {
            Console.Write($"\nWhere would you like to place your X? ");

            try
            {
                userSquare = Convert.ToInt32(Console.ReadLine());
            }
            catch (FormatException)
            {
                Console.Clear();
                Console.Write("You must enter an integer. Press any key to continue: ");
                Console.ReadKey();
                Console.Clear();
            }
            catch (OverflowException)
            {
                Console.Clear();
                Console.Write("That value is too large. Press any key to continue: ");
                Console.ReadKey();
                Console.Clear();
            }


            if (userSquare < 4)
            {
                if (theBoard[0, userSquare - 1] != " ")
                {
                    Console.WriteLine("That square is occupied.  Try again.");
                    continue;
                }
                theBoard[0, userSquare - 1] = "X";
                placesFilled++;
            }
            else if (userSquare < 7)
            {
                if (theBoard[1, userSquare - 4] != " ")
                {
                    Console.WriteLine("That square is occupied.  Try again.");
                    continue;
                }
                theBoard[1, userSquare - 4] = "X";
                placesFilled++;
            }
            else if (userSquare < 10)
            {
                if (theBoard[2, userSquare - 7] != " ")
                {
                    Console.WriteLine("That square is occupied.  Try again.");
                    continue;
                }
                theBoard[2, userSquare - 7] = "X";
                placesFilled++;
            }
            else
            {
                Console.WriteLine("You must select a value from 1 - 9");
            }
            playerTurn = false;
            winCheck = "X";
        }
        else
        {
            computerSquare = myRandomGenerator.Next(1, 10);
            //Console.WriteLine(computerSquare);

            if (computerSquare < 4)
            {
                if (theBoard[0, computerSquare - 1] != " ")
                {

                    continue;
                }
                theBoard[0, computerSquare - 1] = "O";
                placesFilled++;
                //break;
            }
            else if (computerSquare < 7)
            {
                if (theBoard[1, computerSquare - 4] != " ")
                {

                    continue;
                }
                theBoard[1, computerSquare - 4] = "O";
                placesFilled++;
                //break;
            }
            else
            {
                if (theBoard[2, computerSquare - 7] != " ")
                {

                    continue;
                }
                theBoard[2, computerSquare - 7] = "O";
                placesFilled++;
                //break;
            }
            playerTurn = true;
            winCheck = "O";
        }
    }

}

static void PrintBoard()
{
    string[,] theBoard = new string[3, 3]
       {   { " ", " ", " "},
                { " ", " ", " "},
                { " ", " ", " "}   };

    Console.Clear();
    Console.WriteLine($" {theBoard[0, 0]} | {theBoard[0, 1]} | {theBoard[0, 2]}");
    Console.WriteLine("---|---|---");
    Console.WriteLine($" {theBoard[1, 0]} | {theBoard[1, 1]} | {theBoard[1, 2]}");
    Console.WriteLine("---|---|---");
    Console.WriteLine($" {theBoard[2, 0]} | {theBoard[2, 1]} | {theBoard[2, 2]}");
}

static void CheckForWinTie()
{
    int computerSquare = 0;
    int userSquare = 0;
    bool playerTurn = true;
    int whoFirst = 0;
    string winCheck = null;
    string[,] theBoard = new string[3, 3]
    {   { " ", " ", " "},
                { " ", " ", " "},
                { " ", " ", " "}   };
    int placesFilled = 0;

    if (theBoard[0, 0] == winCheck && theBoard[0, 1] == winCheck && theBoard[0, 2] == winCheck)
    {
        if (winCheck == "X")
        {
            Console.WriteLine("\nYou have won");
            Console.ReadKey();

        }
        else
        {
            Console.WriteLine("\nThe computer has won");
            Console.ReadKey();

        }
    }

    if (theBoard[1, 0] == winCheck && theBoard[1, 1] == winCheck && theBoard[1, 2] == winCheck)
    {
        if (winCheck == "X")
        {
            Console.WriteLine("\nYou have won");
            Console.ReadKey();

        }
        else
        {
            Console.WriteLine("\nThe computer has won");
            Console.ReadKey();

        }

    }
    if (theBoard[2, 0] == winCheck && theBoard[2, 1] == winCheck && theBoard[2, 2] == winCheck)
    {
        if (winCheck == "X")
        {
            Console.WriteLine("\nYou have won");
            Console.ReadKey();

        }
        else
        {
            Console.WriteLine("\nThe computer has won");
            Console.ReadKey();

        }

    }


    if (theBoard[0, 0] == winCheck && theBoard[1, 0] == winCheck && theBoard[2, 0] == winCheck)
    {
        if (winCheck == "X")
        {
            Console.WriteLine("\nYou have won");
            Console.ReadKey();

        }
        else
        {
            Console.WriteLine("\nThe computer has won");
            Console.ReadKey();

        }
    }
    if (theBoard[0, 1] == winCheck && theBoard[1, 1] == winCheck && theBoard[2, 1] == winCheck)
    {
        if (winCheck == "X")
        {
            Console.WriteLine("\nYou have won");
            Console.ReadKey();

        }
        else
        {
            Console.WriteLine("\nThe computer has won");
            Console.ReadKey();

        }


    }
    if (theBoard[0, 2] == winCheck && theBoard[1, 2] == winCheck && theBoard[2, 2] == winCheck)
    {
        if (winCheck == "X")
        {
            Console.WriteLine("\nYou have won");
            Console.ReadKey();

        }
        else
        {
            Console.WriteLine("\nThe computer has won");
            Console.ReadKey();

        }
    }

    if (theBoard[0, 0] == winCheck && theBoard[1, 1] == winCheck && theBoard[2, 2] == winCheck)
    {
        if (winCheck == "X")
        {
            Console.WriteLine("\nYou have won");
            Console.ReadKey();

        }
        else
        {
            Console.WriteLine("\nThe computer has won");
            Console.ReadKey();

        }


    }

    if (theBoard[0, 2] == winCheck && theBoard[1, 1] == winCheck && theBoard[0, 0] == winCheck)
    {
        if (winCheck == "X")
        {
            Console.WriteLine("\nYou have won");
            Console.ReadKey();

        }
        else
        {
            Console.WriteLine("\nThe computer has won");
            Console.ReadKey();
        }


    }

    if (placesFilled == 9)
    {
        Console.WriteLine("\nIt's a tie");
        Console.ReadKey();

    }
}

Console.Write("\n(Y) to play again: ");
    string playAgain = Console.ReadLine();
    if (playAgain != "Y" && playAgain != "y")
    {
        break;
    }
Console.Clear();

}

1 Ответ

0 голосов
/ 25 марта 2019

Я думаю, что вы спрашиваете о параметрах метода и типах возвращаемых данных.

public int Add(int x, int y)
{
   return x + y;
}

В этом примере Add - это имя метода, int - тип возвращаемого значения метода, int x и int y - параметры. Когда вы говорите, что хотите «использовать данные из предыдущего», я думаю, что вам нужно передать данные из одного метода в другой. Допустим, я хотел получить номер от пользователя. Я мог бы иметь такой метод:

public int GetUserAnswer()
{
   Console.Write("Enter a number");
   if(int.TryParse(Console.ReadLine(), out int number))
     return number;
   return -1;
}

Тогда у меня мог бы быть метод, который соединит их вместе.

public void Foo()
{
   int userNumber = GetUserAnswer();
   int userNumber2 = GetUserAnswer();
   int sum = Add(userNumber, userNumber2);
   //do more stuff
}

Теперь у вас есть два метода, работающих вместе. Первый получает номер от пользователя и возвращает его. Второй берет 2 числа, которые мы ранее получили от пользователя, складывает их вместе и возвращает сумму. Надеюсь, это поможет.

Что касается вашего вопроса о том, как и где разбить код большего размера, поищите места, где либо блок кода повторяется, либо места, где несколько операторов сочетаются друг с другом и выполняют только одно. Например,

public int HandleUserSqaureLessThan4(string[,] theBoard, int userSquare, int PlacesFilled)
{
   if (theBoard[0, userSquare - 1] != " ")
            {
                Console.WriteLine("That square is occupied.  Try again.");
                continue;
            }
            theBoard[0, userSquare - 1] = "X";
            return placesFilled++;
}

Тогда вы можете получить что-то вроде этого:

if (userSquare < 4)
{
    HandleUserSqaureLessThan4(theBoard, userSquare, placesFilled);
}
... //the rest of the code
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...