как сделать стенку для игры змея в C# - PullRequest
0 голосов
/ 30 апреля 2020

Я сделал игру со змеями, но теперь я хочу добавить в терминал функцию, позволяющую игроку выбирать режим привязки к режиму игры (стена) и режим без привязки (стена отсутствует). Я хочу знать, как я могу сделать стену, поскольку я видел некоторые проекты, использующие символы, такие как «#», и когда голова змеи ударяется о стену, игрок проигрывает игру.

'        static void Main(string[] args)
        {

            byte right = 0;
            byte left = 1;
            byte down = 2;
            byte up = 3;
            int currentTime = Environment.TickCount;
            int lastFoodTime = 0;
            int foodDissapearTime = 10000; //food dissappears after 10 second 
            int negativePoints = 0;
            Position[] directions = new Position[4];

            Program p = new Program();
            //display start screen before background music and game start 
            p.DisplayStartScreen();
            //Play background music
            p.BackgroundMusic();

            // Define direction with characteristic of index of array
            p.Direction(directions);

            // Initialised the obstacles location at the starting of the game
            List<Position> obstacles = new List<Position>();
            p.InitialRandomObstacles(obstacles);

            //Do the initialization for sleepTime (Game's Speed), Snake's direction and food timing
            //Limit the number of rows of text accessible in the console window
            double sleepTime = 100;
            int direction = right;
            Random randomNumbersGenerator = new Random();
            Console.BufferHeight = Console.WindowHeight;
            lastFoodTime = Environment.TickCount;

            //Initialise the snake position in top left corner of the windows
            //Havent draw the snake elements in the windows yet. Will be drawn in the code below
            Queue<Position> snakeElements = new Queue<Position>();
            for (int i = 0; i <= 3; i++) // Length of the snake was reduced to 3 units of *
            {
                snakeElements.Enqueue(new Position(0, i));
            }

            //To position food randomly when the program runs first time
            Position food = new Position();
            p.GenerateFood(ref food,snakeElements,obstacles);

            //while the game is running position snake on terminal with shape "*"
            foreach (Position position in snakeElements)
            {
                Console.SetCursorPosition(position.col, position.row);
                p.DrawSnakeBody();
            }

            while (true)
            {
                //negative points is initialized as 0 at the beginning of the game. As the player reaches out for food
                //negative points increment depending how far the food is
                negativePoints++;

                //Check the user input direction
                p.CheckUserInput(ref direction, right, left, down, up);

                //When the game starts the snake head is towards the end of his body with face direct to start from right.
                Position snakeHead = snakeElements.Last();
                Position nextDirection = directions[direction];

                //Snake position to go within the terminal window assigned.
                Position snakeNewHead = new Position(snakeHead.row + nextDirection.row,
                    snakeHead.col + nextDirection.col);

                if (snakeNewHead.col < 0) snakeNewHead.col = Console.WindowWidth - 1;
                if (snakeNewHead.row < 0) snakeNewHead.row = Console.WindowHeight - 1;
                if (snakeNewHead.row >= Console.WindowHeight) snakeNewHead.row = 0;
                if (snakeNewHead.col >= Console.WindowWidth) snakeNewHead.col = 0;

                //Check for GameOver Criteria
                int gameOver=p.GameOverCheck(currentTime, snakeElements, snakeNewHead, negativePoints,obstacles);
                if (gameOver == 1)
                    return;

                //Check for Winning Criteria
                int winning = p.WinningCheck(snakeElements, negativePoints);
                if (winning == 1) return;

                //The way snake head will change as the player changes his direction
                Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                p.DrawSnakeBody();

                //Snake head shape when the user presses the key to change his direction
                snakeElements.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                Console.ForegroundColor = ConsoleColor.Gray;
                if (direction == right) Console.Write(">"); //Snake head when going right
                if (direction == left) Console.Write("<");//Snake head when going left
                if (direction == up) Console.Write("^");//Snake head when going up
                if (direction == down) Console.Write("v");//Snake head when going down


                // food will be positioned randomly until they are not at the same row & column as snake head
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                {
                    Console.Beep();// Make a sound effect when food was eaten.
                    p.GenerateFood(ref food, snakeElements, obstacles);


                    //when the snake eat the food, the system tickcount will be set as lastFoodTime
                    //new food will be drawn, snake speed will increases
                    lastFoodTime = Environment.TickCount;
                    sleepTime--;

                    //Generate new obstacle
                    p.GenerateNewObstacle(ref food,snakeElements,obstacles);

                }
                else
                {
                    // snake is moving
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(" ");
                }

                //if snake did not eat the food before it disappears, 50 will be added to negative points
                //draw new food after the previous one disappeared
                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints = negativePoints + 50;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write(" ");

                    //Generate the new food and record the system tick count
                    p.GenerateFood(ref food, snakeElements, obstacles);
                    lastFoodTime = Environment.TickCount;
                }

                //snake moving speed increased 
                sleepTime -= 0.01;

                //pause the execution thread of snake moving speed
                Thread.Sleep((int)sleepTime);
            }
        }
    }
}'

1 Ответ

0 голосов
/ 30 апреля 2020

В вашем коде есть все необходимое; вы строите состояние своей игры до того, как запускается основной l oop, затем вы проверяете пользовательский ввод, выполняете обнаружение столкновений, проверяете сценарий окончания игры ios, рисует обновления тела змеи по заданному c позиций на экране и т. Д. c.

Поведение стены и ее проверка на столкновение не сильно отличаются от поведения тела змеи, но установка стены - это то, что вы хотите сделать перед основной игрой l oop, и это то, что не нужно ставить в очередь / убирать, как положения тела змеи.

Что если вы добавите некоторый установочный код до того, как ваша основная игра l oop начнет создавать List из Position для хранения стен, а затем сгенерирует for l oop, чтобы попытаться добавить Положения стены к списку и отрисовки их на консоли в зависимости от размера окна консоли? Вы знаете ограничения x и y консоли, поскольку вы уже используете их при проверке положения головы змеи; во время вашей основной игры l oop вы можете проверять наличие столкновений со списком позиций на стене так же, как вы делаете список позиций тела змеи, и ваша игра ведет себя соответствующим образом.

Разделение проблемы на отдельные шаги вероятно, хорошее начало.

  1. Как нарисовать прямоугольник на консоли?
  2. Как нарисовать этот прямоугольник перед началом игры?
  3. Как мне заставить прямоугольник заполнить пространство, которое я хочу?
  4. Как отследить, где я нарисовал прямоугольник, чтобы я мог проверить, попала ли на него змея?
  5. Как проверить, попала ли змея одно из положений стены во время основной игры l oop?
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...