예제 #1
0
        static void Loop(object obj)
        {
            if (walls.IsHit(snake.GetHead()) || snake.IsHit(snake.GetHead()))
            {
                time.Change(0, Timeout.Infinite);
                Console.SetCursorPosition(X / 2, Y / 2);

                Console.Write("Game over");
            }
            else if (snake.Eat(foodFactory.food))
            {
                foodFactory.CreateFood();
            }
            else
            {
                snake.Move();
            }
            Console.SetCursorPosition(1, 30);
            Console.Write(snake.score);
        }
예제 #2
0
        private void Update(object sender, EventArgs e)
        {
            this.Text = string.Format("Snake - Score: {0}", score);
            snake.Move(direction);

            for (int i = 1; i < snake.Body.Length; i++)
            {
                if (snake.Body[0].IntersectsWith(snake.Body[i])) //Death by cannibalism..
                {
                    Restart();
                }
                if (snake.Body[0].X < 0 || snake.Body[0].X < 290 || snake.Body[0].Y < 0 || snake.Body[0].Y < 190) //hitting the wall..
                {
                    Restart();
                }
                if (snake.Body[0].IntersectsWith(food.Piece))  //Eating food and growing..
                {
                    score++;
                    snake.Grow();
                    food.Generate(rand);
                }
            }
            this.Invalidate();
        }
예제 #3
0
        static void Main(string[] args)
        {
            Console.SetBufferSize(sizeX, sizeY); // Размер консольки
            Console.Title = "Змейка";

startProgramm:             // Метка для начала работы программы

            Console.Clear();
            Console.ForegroundColor = ConsoleColor.White;

            Walls walls = new Walls(sizeX, sizeY);

            walls.Draw();

            // Отрисовка точек
            Point p     = new Point(4, 5, '*');
            Snake snake = new Snake(p, 4, Direction.RIGHT);

            snake.Draw();

            byte snakeSpeed = 150;
            int  ochki      = 0;

            FoodCreator foodCreator = new FoodCreator(sizeX, sizeY, '$');
            Point       food        = foodCreator.CreateFood();

            food.Draw();

            while (true)
            {
                if (walls.IsHit(snake) || snake.IsHitTail())
                {
                    break;
                }

                Thread.Sleep(snakeSpeed);

                if (snake.Eat(food))
                {
                    food = foodCreator.CreateFood();
                    ochki++;
                    food.Draw();
                    if ((snakeSpeed <= 70) && (snakeSpeed > 55))
                    {
                        snakeSpeed -= 15;
                    }
                    else if ((snakeSpeed <= 55) && (snakeSpeed > 45))
                    {
                        snakeSpeed -= 10;
                    }
                    else if ((snakeSpeed <= 45) && (snakeSpeed > 35))
                    {
                        snakeSpeed -= 5;
                    }
                    else if ((snakeSpeed <= 35) && (snakeSpeed > 20))
                    {
                        snakeSpeed -= 3;
                    }
                    else if (snakeSpeed <= 20)
                    {
                        snakeSpeed = 20;
                    }
                    else
                    {
                        snakeSpeed -= 20;
                    }
                }
                else
                {
                    snake.Move();
                }



                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo key = Console.ReadKey();
                    snake.HandleKey(key.Key);
                }
            }
metka1:
            WriteGameOver(ochki);

            ConsoleKeyInfo key1 = Console.ReadKey();

            if ((key1.Key != ConsoleKey.Enter) && (key1.Key != ConsoleKey.Escape))
            {
                goto metka1;
            }
            else if (key1.Key == ConsoleKey.Enter)
            {
                goto startProgramm;
            }
            else if (key1.Key == ConsoleKey.Escape)
            {
                return;
            }
        }
예제 #4
0
        static void Main(string[] args)
        {
            Console.SetBufferSize(80, 25);


            // Draw Lines
            HorizontalLine line = new HorizontalLine(0, 78, 0, '+');

            line.Drow();

            VerticalLine line2 = new VerticalLine(0, 24, 0, '+');

            line2.Drow();

            VerticalLine line3 = new VerticalLine(0, 24, 78, '+');

            line3.Drow();

            HorizontalLine line4 = new HorizontalLine(0, 78, 24, '+');

            line4.Drow();



            //Draw point
            Point p     = new Point(4, 5, '*');
            Snake snake = new Snake(p, 4, Direction.RIGHT);

            snake.Drow();


            FoodCreator foodCreator = new FoodCreator(80, 25, '$');
            Point       food        = foodCreator.CreateFood();

            food.Draw();



            while (true)
            {
                if (snake.Eat(food))
                {
                    food = foodCreator.CreateFood();
                    food.Draw();
                }
                else
                {
                    snake.Move();
                }
            }
            while (true)
            {
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo key = Console.ReadKey();
                    snake.HandleKey(key.Key);
                }
                Thread.Sleep(100);
                snake.Move();
            }


            Console.ReadLine();
        }
예제 #5
0
        static void Main(string[] args)
        {
            StartOfTheGame.StartText();
            int  snakeSpeed   = 100;
            bool correctLevel = false;

            string userLevel = Console.ReadLine();

            while (!correctLevel)
            {
                if (int.TryParse(userLevel, out int choosedLevel))
                {
                    if (choosedLevel == 1 || choosedLevel == 2 || choosedLevel == 3 || choosedLevel == 4)
                    {
                        snakeSpeed   = Levels.ReturnSpeed(choosedLevel);
                        correctLevel = true;
                    }
                    else
                    {
                        Console.WriteLine("Incorrect level. Try again");
                        userLevel = Console.ReadLine();
                    }
                }
                else
                {
                    Console.WriteLine("Error! It wasn`t a number. Please, try again");
                    userLevel = Console.ReadLine();
                }
            }
            Console.Clear();

            int    mapWeidth = 80;
            int    mapHeight = 25;
            Random rnd       = new Random();
            Walls  walls     = new Walls(mapWeidth, mapHeight);

            walls.Draw();


            Point startTailPoint = new Point(rnd.Next(5, mapWeidth - 5), rnd.Next(5, mapHeight - 5), '*');
            Snake snake          = new Snake(startTailPoint, 5, Direction.Right);

            snake.Draw();

            FoodCreator foodCreator  = new FoodCreator(mapWeidth - 2, mapHeight - 2);
            Point       foodForSnake = foodCreator.CreateFood(snake);

            foodCreator.Draw();

            while (true)
            {
                if (walls.IsHit(snake) || snake.IsHitWithTail())
                {
                    break;
                }
                if (snake.Eat(foodForSnake))
                {
                    foodForSnake = foodCreator.CreateFood(snake);
                    foodCreator.Draw();
                }
                else
                {
                    snake.Move();
                }
                Thread.Sleep(snakeSpeed);

                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo enteredKey = Console.ReadKey();
                    snake.EnteredKey(enteredKey);
                }
            }

            EndOfGame theEnd = new EndOfGame();

            theEnd.EndGameResult(snake, mapWeidth, mapHeight);
            theEnd.DrawEndGameResult();
            Console.ReadLine();
        }
예제 #6
0
        // Plays the game itself
        public static int Game(int refreshRate, int numCones, int snakeLength)
        {
            // Set the game parameters based on the arguments
            Program.REFRESH_RATE = refreshRate;
            Program.NUM_CONES    = numCones;
            Program.START_LEN    = snakeLength;

            int pixelsToMove = 0;                   // Number of pixels for the snake to move from a given frame to the next (initialized to zero to circumvent "unassigned variable" errors)
            int score        = 0;                   // Final score = # of pieces of food eaten
            // Since the length increases by exactly one for each food: final score = final length - initial length of snake (+1 because the tail gets deleted during the final move)
            Random rand        = new Random();      // Used to randomly generate the position of the cones
            int    START_X_VAL = 5 + Program.START_LEN;
            int    START_Y_VAL = SCREEN_HEIGHT / 2;

            // Initialize all relevant objects
            Screen GameScreen = new Screen(1, 2, SCREEN_WIDTH - 2, SCREEN_HEIGHT - 1, 'X');
            Snake  snake      = new Snake(START_X_VAL, START_Y_VAL, GameScreen);
            int    yVal;            // Temporarily contains the ranomly generated y-coordinate for each cone's positions (need to check if this value is equal to starting y-coordinate)

            // Randomly place the required number of cones
            for (int i = 0; i < Program.NUM_CONES; i++)
            {
                do
                {
                    yVal = rand.Next(3, SCREEN_HEIGHT - 2);
                } while (yVal == START_Y_VAL);                  // Don't print cones on the starting line

                new Cone(rand.Next(2, SCREEN_WIDTH - 2), yVal, GameScreen);
            }
            Food food = new Food();

            food.Spawn(GameScreen, snake);

            GameScreen.PrintFullScreen(snake, food);

            // Initialize scoreboard
            Console.SetCursorPosition(0, 0);
            Console.BackgroundColor = ConsoleColor.DarkGray;                // Print dark gray background
            for (int y = 0; y < 2; y++)
            {
                for (int x = 0; x <= 22; x++)
                {
                    Console.SetCursorPosition(x, y);
                    Console.Write(' ');
                }
            }
            Console.ForegroundColor = ConsoleColor.White;
            Console.SetCursorPosition(0, 0);
            Console.WriteLine("SCORE: 0");
            Console.WriteLine("OLD HIGH SCORE: {0}", Program.highScore);

            // Print initial messages (but don't save them to the list)
            // First make space on screen by printng dark gray rectangle
            Console.BackgroundColor = ConsoleColor.DarkGray;
            for (int y = 11; y <= 15; y++)
            {
                for (int x = SCREEN_WIDTH / 2 - 34; x <= SCREEN_WIDTH / 2 + 34; x++)
                {
                    Console.SetCursorPosition(x, y);
                    Console.Write(' ');
                }
            }
            // Then print messages
            Console.SetCursorPosition(SCREEN_WIDTH / 2 - 12, 12);
            Console.Write("Press any key to start...");
            Console.SetCursorPosition(SCREEN_WIDTH / 2 - 32, 14);
            Console.Write("Once the game starts, press CTRL + X to return to the main menu");

            Console.ResetColor();               // Reset background colour to default
            Console.ReadKey(true);

            // Once the game starts, clear messages from the screen
            GameScreen.PrintFullScreen(snake, food, SCREEN_WIDTH / 2 - 34, 11, SCREEN_WIDTH / 2 + 34, 15); // Print screen between (SCREEN_WIDTH/2 - 34, 11) and (SCREEN_WIDTH/2 + 34, 15)

            ConsoleKeyInfo cki = new ConsoleKeyInfo();                                                     // Create ConsoleKeyInfo object to receive user keystrokes

            while (!snake.dead)
            {
                // If the user presses a key, update the snake's velocity
                if (Console.KeyAvailable)
                {
                    cki = Console.ReadKey(true);
                    switch (cki.Key)
                    {
                    case ConsoleKey.UpArrow:                                    // If the user presses the up arrow or 'W', the snake moves up
                    case ConsoleKey.W:
                        snake.SetVelocity(0, yVelocity);
                        break;

                    case ConsoleKey.DownArrow:                                  // If the user presses the down arrow or 'S', the snake moves down
                    case ConsoleKey.S:
                        snake.SetVelocity(0, -yVelocity);
                        break;

                    case ConsoleKey.RightArrow:                                 // If the user presses the right arrow or 'D', the snake moves to the right
                    case ConsoleKey.D:
                        snake.SetVelocity(xVelocity, 0);
                        break;

                    case ConsoleKey.LeftArrow:                                  // If the use presses the left arrow or 'A', the snake moves to the left
                    case ConsoleKey.A:
                        snake.SetVelocity(-xVelocity, 0);
                        break;

                    case ConsoleKey.X:                                          // If the user presses CTRL + X, end the game
                        if (cki.Modifiers == ConsoleModifiers.Control)
                        {
                            snake.dead = true;
                        }
                        snake.segmentList.RemoveAt(snake.segmentList.Count - 1);                                    // Delete the tail so that the score is displayed properly
                        break;

                    default:
                        break;
                    }
                }

                if (snake.v_x == 0)                         // Moving vertically
                {
                    pixelsToMove = Math.Abs(snake.v_y);
                }
                else if (snake.v_y == 0)                    // Moving horizontally
                {
                    pixelsToMove = Math.Abs(snake.v_x);
                }
                for (int i = 0; i < pixelsToMove; i++)
                {
                    if (!snake.dead)
                    {                           // Avoid "index out of range" errors by stopping snake before it leaves screen
                        snake.Move(GameScreen, food);
                        food.Spawn(GameScreen, snake);
                    }
                }

                GameScreen.PrintScreen(snake, food);                    // Print the updated screen

                System.Threading.Thread.Sleep(1000 / REFRESH_RATE);     // Wait until it's time to print the next frame (assume the execution time for a single frame is negligible)
            }

            // Create a dark gray rectangle in the center of the screen for the GAME OVER message
            Console.BackgroundColor = ConsoleColor.DarkGray;
            for (int y = 11; y <= 17; y++)
            {
                for (int x = SCREEN_WIDTH / 2 - 23; x <= SCREEN_WIDTH / 2 + 23; x++)
                {
                    Console.SetCursorPosition(x, y);
                    Console.Write(' ');
                }
            }

            // Print GAME OVER message, display score, and prompt them to return to the main menu
            Console.SetCursorPosition(SCREEN_WIDTH / 2 - 5, 12);
            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write("GAME  OVER");
            Console.ForegroundColor = ConsoleColor.White;

            System.Threading.Thread.Sleep(750);

            score = snake.segmentList.Count - Program.START_LEN + 1;
            if (score <= highScore)
            {
                Console.SetCursorPosition(SCREEN_WIDTH / 2 - 7, 14);
                Console.Write("Final Score: {0}", score);
            }
            else
            {
                Console.SetCursorPosition(SCREEN_WIDTH / 2 - 16, 14);
                Console.Write("Final Score: {0} (", score);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("NEW HIGH SCORE!");
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write(")");
            }

            System.Threading.Thread.Sleep(750);

            Console.SetCursorPosition(SCREEN_WIDTH / 2 - 19, 16);
            Console.Write("Press ENTER to return to the main menu");
            Console.ResetColor();
            while (true)
            {
                if (Console.ReadKey(true).Key == ConsoleKey.Enter)
                {
                    break;
                }
            }

            // Return the current score if it's a new high score
            if (score > Program.highScore)
            {
                return(score);
            }
            else
            {
                return(Program.highScore);
            }
        }