Exemplo n.º 1
0
        /// <summary>
        /// This function starts the game
        /// </summary>
        /// <param name="delay">Delay value returned from <see cref="ChooseLevel"/></param>
        /// /// <param name="score">User's score after losing the game</param>
        /// <returns>The game status which is whether won or lost. See also <seealso cref="GameStatus"/></returns>
        static GameStatus Snake(int delay, out int score)
        {
            // Few requirements before the game starts
            Board     gameBoard = new Board();
            SnakePart head      = new SnakePart(Point.ToPoint(gameBoard.Width / 2, gameBoard.Height / 2 - 1));

            gameBoard.AddSnake(head.Location);
            List <SnakePart> snakeParts = new List <SnakePart> {
                new SnakePart(Point.ToPoint(gameBoard.Width / 2, gameBoard.Height / 2))
            };

            gameBoard.AddSnake(snakeParts[0].Location);
            SnakePart tail = new SnakePart(Point.ToPoint(gameBoard.Width / 2, gameBoard.Height / 2 + 1));

            gameBoard.AddSnake(tail.Location);
            Direction headDirection = Direction.Up;

            gameBoard.SetFruitLocation();
            while (true)
            {
                do
                {
                    GameStatus status = SnakePart.SnakeMove(head, snakeParts, tail, gameBoard, headDirection);
                    if (status != GameStatus.StillPlaying)
                    {
                        score = snakeParts.Count - 1;
                        return(status); // The game status is whether won or lost
                    }

                    Thread.Sleep(delay);
                } while (!Console.KeyAvailable);   // Checks if the user wants to change the direction

                switch (Console.ReadKey(true).Key) // Changing the direction if it is possible
                {
                case ConsoleKey.UpArrow:
                    if (headDirection != Direction.Down)
                    {
                        headDirection = Direction.Up;
                    }
                    break;

                case ConsoleKey.DownArrow:
                    if (headDirection != Direction.Up)
                    {
                        headDirection = Direction.Down;
                    }
                    break;

                case ConsoleKey.LeftArrow:
                    if (headDirection != Direction.Right)
                    {
                        headDirection = Direction.Left;
                    }
                    break;

                case ConsoleKey.RightArrow:
                    if (headDirection != Direction.Left)
                    {
                        headDirection = Direction.Right;
                    }
                    break;

                default:
                    continue;
                }
            }
        }