Exemplo n.º 1
0
        static void Main(string[] args)
        {
            Position[] directions = new Position[]
            {
                new Position(0, 1),  // right
                new Position(0, -1), //left
                new Position(1, 0),  //down
                new Position(-1, 0), //top
            };

            int direction = 0;

            Console.BufferHeight = Console.WindowHeight;
            Random   randomNumGenerator = new Random();
            Position food = new Position(randomNumGenerator.Next(0, Console.WindowHeight), randomNumGenerator.Next(0, Console.WindowWidth));

            Console.SetCursorPosition(food.row, food.col);
            Console.Write("@");
            Queue <Position> snakeElements = new Queue <Position>();

            for (int i = 0; i < 6; i++)
            {
                snakeElements.Enqueue(new Position(0, i));
            }
            foreach (Position position in snakeElements)
            {
                Console.SetCursorPosition(position.col, position.row);
                Console.Write("*");
            }


            while (true)
            {
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userInput = Console.ReadKey();

                    if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        direction = 0;
                    }
                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        direction = 1;
                    }
                    if (userInput.Key == ConsoleKey.DownArrow)
                    {
                        direction = 2;
                    }
                    if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        direction = 3;
                    }
                }


                Position snakeHead     = snakeElements.Last();
                Position nextDirection = directions[direction];
                Position snakeNewHead  = new Position(snakeHead.row + nextDirection.row, snakeHead.col + nextDirection.col);

                if (snakeNewHead.row < 0 ||
                    snakeNewHead.col < 0 || snakeNewHead.row >= Console.WindowHeight ||
                    snakeNewHead.col >= Console.WindowWidth || snakeElements.Contains(snakeNewHead))
                {
                    //Console.Clear();
                    Console.SetCursorPosition(0, 0);
                    Console.WriteLine("GAME OVER!!!");
                    Console.WriteLine($"YOUR SCORE : {(snakeElements.Count-6)*10 }");
                    return;
                }
                snakeElements.Enqueue(snakeNewHead);
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                {
                    food = new Position(randomNumGenerator.Next(0, Console.BufferHeight), randomNumGenerator.Next(0, Console.BufferWidth));
                }
                else
                {
                    snakeElements.Dequeue();
                }


                Console.Clear();

                foreach (Position position in snakeElements)
                {
                    Console.SetCursorPosition(position.col, position.row);
                    Console.Write("*");
                }

                Console.SetCursorPosition(food.row, food.col);
                Console.Write("@");

                Thread.Sleep(200);
            }
        }
Exemplo n.º 2
0
        public static int lives = 3; // initialize the lives of the snake, in this case: 3.
        static void Main(string[] args)
        {
            // calling the main menu;
            start start = new start();

            start.mainmenu();

            var    move    = new System.Media.SoundPlayer();
            string move1   = @"move.wav";
            string movewav = Path.GetFullPath(move1);

            move.SoundLocation = movewav;
            System.Media.SoundPlayer eat = new System.Media.SoundPlayer();
            string eat1   = @"eat.wav";
            string eatwav = Path.GetFullPath(eat1);

            eat.SoundLocation = eatwav;
            System.Media.SoundPlayer gameover = new System.Media.SoundPlayer();
            string gameover1   = @"gameover.wav";
            string gameoverwav = Path.GetFullPath(gameover1);

            gameover.SoundLocation = gameoverwav;
            System.Media.SoundPlayer crash = new System.Media.SoundPlayer();
            string crash1   = @"crash.wav";
            string crashwav = Path.GetFullPath(crash1);

            crash.SoundLocation = crashwav;
            System.Media.SoundPlayer powerupsound = new System.Media.SoundPlayer();
            string powerup1   = @"powerup.wav";
            string powerupwav = Path.GetFullPath(powerup1);

            powerupsound.SoundLocation = powerupwav;
            byte   right             = 0;
            byte   left              = 1;
            byte   down              = 2;
            byte   up                = 3;
            int    lastFoodTime      = 0;
            int    foodDissapearTime = 12000;
            int    negativePoints    = 0;
            double sleepTime         = 100;
            int    direction         = right; // To make the snake go to the right when the program starts

            Random randomNumbersGenerator = new Random();

            Console.BufferHeight = Console.WindowHeight;
            lastFoodTime         = Environment.TickCount;

            // Make sure the snake spawn with just 3 "*"s and spawn it on the top left of the screen

            Queue <Position> snakeElements = new Queue <Position>();

            for (int i = 0; i <= 3; i++) //spawn snake body
            {
                snakeElements.Enqueue(new Position(0, i));
            }

            List <Position> Scoreboard = new List <Position>() // scoreboard boundaries
            {
                new Position(1, 20)
            };

            // Spawn the first 5 obstacles in the game

            List <Position> obstacles = new List <Position>() //spawn the first obstacles
            {
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
            };

            foreach (Position obstacle in obstacles) //write obstacle as "=" on declared position
            {
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.SetCursorPosition(obstacle.y, obstacle.x);
                Console.Write("▒");
            }

            List <Position> powerups = new List <Position>()
            {
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth))
            };

            foreach (Position powerup in powerups) // powerup is created
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.SetCursorPosition(powerup.y, powerup.x);
                Console.Write("+");
            }

            Position food;

            do //randomize where the food spawns
            {
                food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                    randomNumbersGenerator.Next(0, Console.WindowWidth));
            }while (snakeElements.Contains(food) || obstacles.Contains(food) || Scoreboard.Contains(food)); //to make sure that food doesnt spawn on both snake, obstacles and scoreboard



            //Movement implementation

            Position[] directions = new Position[]
            {
                new Position(0, 1),  // right
                new Position(0, -1), // left
                new Position(1, 0),  // down
                new Position(-1, 0), // up
            };

            while (true) //read the direction of arrow key which user inputted
            {
                negativePoints++;

                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userInput = Console.ReadKey(true);
                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        if (direction != right)
                        {
                            direction = left;
                        }
                        move.Play();
                    }
                    if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        if (direction != left)
                        {
                            direction = right;
                        }
                        move.Play();
                    }
                    if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        if (direction != down)
                        {
                            direction = up;
                        }
                        move.Play();
                    }
                    if (userInput.Key == ConsoleKey.DownArrow)
                    {
                        if (direction != up)
                        {
                            direction = down;
                        }
                        move.Play();
                    }
                }


                //Creating the snake:

                Position snakeHead     = snakeElements.Last();  //make sure the head of the snake is spawned at the end of the "*" position
                Position nextDirection = directions[direction]; //initialize which direction is inputted

                Position snakeNewHead = new Position(snakeHead.x + nextDirection.x,
                                                     snakeHead.y + nextDirection.y); //snakehead will move to the same direction to which the user inputted

                // make sure the snake wont be able to go outside the screen
                if (snakeNewHead.y < 0)
                {
                    if (snakeNewHead.x == 0)
                    {
                        snakeNewHead.y = Console.WindowWidth - 21;
                    }

                    else
                    {
                        snakeNewHead.y = Console.WindowWidth - 1;
                    }
                }
                if (snakeNewHead.x < 0)
                {
                    snakeNewHead.x = Console.WindowHeight - 1;
                }
                if (snakeNewHead.x >= Console.WindowHeight)
                {
                    if (snakeNewHead.y >= 20)
                    {
                        snakeNewHead.x = 1;
                    }

                    else
                    {
                        snakeNewHead.x = 0;
                    }
                }
                if (snakeNewHead.y >= Console.WindowWidth)
                {
                    snakeNewHead.y = 0;
                }
                if (snakeNewHead.y >= Console.WindowWidth - 20 && snakeNewHead.x < 1) //scoreboard boundaries
                {
                    if (snakeNewHead.x == 1)
                    {
                        snakeNewHead.y = 0;
                    }

                    else
                    {
                        snakeNewHead.x = Console.WindowHeight - 1;
                    }
                }

                foreach (Position position in snakeElements) //writes the body of the snake as "*" on declared position
                {
                    Console.SetCursorPosition(position.y, position.x);
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.Write("*");
                }

                int userPoints = (snakeElements.Count - 4) * 100;

                // Show and update the score of the player

                Console.ForegroundColor = ConsoleColor.Red;
                Console.SetCursorPosition(Console.WindowWidth - 10, 0);
                Console.Write("Score: ");
                Console.ForegroundColor = ConsoleColor.White;
                Console.SetCursorPosition(Console.WindowWidth - 3, 0);
                Console.Write(userPoints);

                // Show and update the lives of the snake

                Console.ForegroundColor = ConsoleColor.Red;
                Console.SetCursorPosition(Console.WindowWidth - 20, 0);
                Console.WriteLine("Lives: ");
                Console.ForegroundColor = ConsoleColor.White;
                Console.SetCursorPosition(Console.WindowWidth - 13, 0);
                Console.Write(lives);

                // the game will be over when the snake hits it body or the obstacles 3 times

                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                {
                    crash.Play();
                    lives -= 1;
                }

                if (snakeElements.Contains(snakeNewHead) || powerups.Contains(snakeNewHead))
                {
                    powerupsound.Play();
                    lives += 1;
                }


                if (lives == 0)
                {
                    gameover.Play();
                    gameover _gameover = new gameover();
                    _gameover.gameoverscr(userPoints);
                    break;
                }

                // The game will be over and user will win if they reached 1000 points
                if (userPoints == 1000)
                {
                    gamevictory _gamevictory = new gamevictory();
                    _gamevictory.gamevictoryscr(userPoints);
                    break;
                }

                // writes the head of the snake as ">","<","^","v" to the position it is declared
                snakeElements.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.y, snakeNewHead.x);
                Console.ForegroundColor = ConsoleColor.Gray;
                if (direction == right)
                {
                    Console.Write(">");
                }
                if (direction == left)
                {
                    Console.Write("<");
                }
                if (direction == up)
                {
                    Console.Write("^");
                }
                if (direction == down)
                {
                    Console.Write("v");
                }


                //What will happened if the snake got fed:
                if (snakeNewHead.y == food.y && snakeNewHead.x == food.x)
                {
                    // Things that will be happening with the FOOD once it got ate by the snake
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), //randomize the new position of the food
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));            //writes "@" to indicate food to the designated position it randomized
                    eat.Play();
                    lastFoodTime = Environment.TickCount;
                    sleepTime--;

                    // Things that will be happening with the OBSTACLE once the FOOD got ate by the snake

                    Position obstacle = new Position(); // randomize the position of the obstacles
                    do
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                                randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(obstacle) ||
                            obstacles.Contains(obstacle) ||
                            (food.x != obstacle.x && food.y != obstacle.y) || Scoreboard.Contains(food)); //
                    obstacles.Add(obstacle);
                    Console.SetCursorPosition(obstacle.y, obstacle.x);
                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    Console.Write("▒");
                }
                else
                {
                    // moving...
                    Position last = snakeElements.Dequeue(); // basically moving the snake and delete the last "body part" of the snake to maintain the length of the snake
                    Console.SetCursorPosition(last.y, last.x);
                    Console.Write(" ");
                }


                // Initialize the time taken for the food to spawn if the snake doesn't eat it

                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints = negativePoints + 50;
                    Console.SetCursorPosition(food.y, food.x);
                    Console.Write(" ");
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food) || Scoreboard.Contains(food));
                    lastFoodTime = Environment.TickCount;
                }

                Console.SetCursorPosition(food.y, food.x);
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.Write("♥♥");
                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            PlayMusic("main");
            byte right = 0;
            byte left  = 1;
            byte down  = 2;
            byte up    = 3;
            //means the last time the snakeElement ate
            int lastFoodTime;
            //the time till the food spawns again
            int           foodDissapearTime  = 10000;
            int           highScoreValue     = highScore();
            int           negativePoints     = 0;
            double        sleepTime          = 100;
            bool          gameFlag           = false;
            bool          menuFlag           = true;
            int           foodCounter        = 0;
            int           specialFoodCounter = 0;
            string        username           = "";
            int           direction;
            int           remainingLives;
            int           prevUserPoints;
            List <string> scoreboard = new List <string>();
            int           windowHeight;
            int           windowWidth;



            //makes the number of rows that can be accessed on a console equal to the height of the window
            Console.BufferHeight = Console.WindowHeight;

            //store the last time the snake ate to time since the console started
            lastFoodTime = Environment.TickCount;

            //initialising important components of the game

            //array storing the direction of snake movement
            Position[] directions;
            //create Position objects and stores them in obstacles
            //These represent the obstacles on screen
            List <Position> obstacles;
            List <Position> Nobstacles;
            //Creates the snake using a queue data structure of length 3
            //Queue operates as a first-in first-out array
            Queue <Position> snakeElements;

            snakeElements = new Queue <Position>();
            //boundaries
            List <Position> leftBoundary;
            List <Position> rightBoundary;
            List <Position> bottomBoundary;

            //snake head position
            Position snakeHead;
            //snake head new position when the snake moves
            Position snakeNewHead;
            //position of the next direction the snake moves
            Position nextDirection;
            //creates the food position that is randomly generated as long as the snake has not eaten the food
            //or the food was generated in place of an obstacle
            Position food;
            //stores specialFood location
            Position specialFood;
            //stores trap location
            Position trap;
            //stores reward location
            Position reward;
            //store menu items
            List <string> menuItem;
            //selected menu item
            int index = 0;
            //User points
            int userPoints;

            //initialises variables before game starts
            initialise();

            //This method contains the menu logic which handles the whole game
            menu();

            //END OF GAME

            //METHOD DEFINITIONS



            //Draws objects on the console
            void Draw(Position pos, string drawable, ConsoleColor color = ConsoleColor.Yellow)
            {
                Console.ForegroundColor = color;
                Console.SetCursorPosition(pos.col, pos.row);
                Console.Write(drawable);
            }

            //initialisation of important variables needed to run the game
            void initialise()
            {
                windowHeight   = Console.WindowHeight;
                windowWidth    = Console.WindowWidth;
                remainingLives = 3;
                prevUserPoints = 0;
                direction      = right;
                //array storing the direction of snake movement
                directions = new Position[]
                {
                    new Position(0, 1),  // right
                    new Position(0, -1), // left
                    new Position(1, 0),  // down
                    new Position(-1, 0), // up
                };

                //create Position objects and stores them in obstacles
                //These represent the obstacles on screen
                obstacles = new List <Position>()
                {
                    //-1 prevents the obstacle from spawaning on the userpoints display
                    newRandomPosition(windowHeight, windowWidth),
                    newRandomPosition(windowHeight, windowWidth),
                    newRandomPosition(windowHeight, windowWidth),
                    newRandomPosition(windowHeight, windowWidth),
                    newRandomPosition(windowHeight, windowWidth),
                };

                //create Position objects and stores them in Nobstacles
                //These represent the Nobstacles on screen
                Nobstacles = new List <Position>()
                {
                    //-1 prevents the Nobstacle from spawaning on the userpoints display
                    newRandomPosition(windowHeight, windowWidth),
                    newRandomPosition(windowHeight, windowWidth),
                    newRandomPosition(windowHeight, windowWidth),
                    newRandomPosition(windowHeight, windowWidth),
                    newRandomPosition(windowHeight, windowWidth),
                };

                //Creates the snake using a queue data structure of length 3
                //sets the length of snake equal to 3
                for (int i = 0; i <= 3; i++)
                {
                    snakeElements.Enqueue(new Position(1, i));
                }
                //boundary
                Boundary();

                //create food
                do
                {
                    food = newRandomPosition(windowHeight, windowWidth);
                }while (snakeElements.Contains(food) || obstacles.Contains(food) || Nobstacles.Contains(food));

                //create special food
                do
                {
                    specialFood = newRandomPosition(windowHeight, windowWidth);
                }while (snakeElements.Contains(food) || obstacles.Contains(food) || Nobstacles.Contains(food));

                //create trap
                do
                {
                    trap = newRandomPosition(windowHeight, windowWidth);
                }while (snakeElements.Contains(trap) || obstacles.Contains(trap) || Nobstacles.Contains(trap));

                //create reward
                do
                {
                    reward = newRandomPosition(windowHeight, windowWidth);
                }while (snakeElements.Contains(reward) || obstacles.Contains(reward) || Nobstacles.Contains(reward));
            }

            //MENU
            void menu()
            {
                //menu
                menuItem = new List <string>()
                {
                    "Play",
                    "Username",
                    "Scoreboard",
                    "Quit"
                };
                Console.CursorVisible = false;

                while (menuFlag)
                {
                    string selectedMenuItem = drawMenu(menuItem);
                    if (selectedMenuItem == "Play")
                    {
                        Console.Clear();
                        menuFlag = false;
                        gameFlag = true;
                        play();
                    }
                    else if (selectedMenuItem == "Username")
                    {
                        Console.Clear();
                        Position userNamePos = new Position((Console.WindowHeight - 1) / 2, ((Console.WindowWidth - 1) / 2) - 10);
                        Draw(userNamePos, "Enter your username: "******"Scoreboard")
                    {
                        Console.Clear();
                        if (scoreboard.Any())
                        {
                            for (int i = 0; i < 10 && i < scoreboard.Count; i++)
                            {
                                Position scoreboardPos = new Position((Console.WindowHeight / 2) + i, (Console.WindowWidth - 1) / 2);
                                Draw(scoreboardPos, scoreboard[i], ConsoleColor.Green);
                            }
                        }
                        else
                        {
                            Position userNamePos = new Position((Console.WindowHeight - 1) / 2, ((Console.WindowWidth - 1) / 2) - 10);
                            Draw(userNamePos, "No stored user scores...", ConsoleColor.Green);
                        }
                        Console.ReadLine();
                    }
                    else if (selectedMenuItem == "Quit")
                    {
                        Environment.Exit(0);
                    }
                }
            }

            //draws menu
            string drawMenu(List <string> items)
            {
                Console.Clear();
                //the line to draw the menu after title
                int      menuLine = 0;
                Position menuPos  = new Position((Console.WindowHeight - 1) / 2 + menuLine, ((Console.WindowWidth - 1) / 2));

                Draw(menuPos, "Snake Game", ConsoleColor.Green);
                menuLine++;
                Position hsPos = new Position((Console.WindowHeight - 1) / 2 + menuLine, ((Console.WindowWidth - 1) / 2));

                Draw(hsPos, $"HighScore To Beat: {highScoreValue}", ConsoleColor.Yellow);
                menuLine++;
                Console.ResetColor();
                if (username != "")
                {
                    prevUserPoints = userExists(username);
                    Draw(new Position((Console.WindowHeight - 1) / 2 + menuLine, ((Console.WindowWidth - 1) / 2)), $"Username: {username} , Previous Points: {prevUserPoints}", ConsoleColor.Green);
                    menuLine++;
                }
                for (int i = 0; i < items.Count; i++)
                {
                    Position menuItemPos = new Position((Console.WindowHeight - 1) / 2 + i + menuLine, ((Console.WindowWidth - 1) / 2));
                    if (i == index)
                    {
                        Console.BackgroundColor = ConsoleColor.Gray;
                        Draw(menuItemPos, items[i], ConsoleColor.Black);
                    }
                    else
                    {
                        Draw(menuItemPos, items[i], ConsoleColor.Gray);
                    }
                    Console.ResetColor();
                }
                ConsoleKeyInfo ckey = Console.ReadKey();

                if (ckey.Key == ConsoleKey.DownArrow)
                {
                    if (index == items.Count - 1)
                    {
                        index = 0;
                    }
                    else
                    {
                        index++;
                    }
                }
                else if (ckey.Key == ConsoleKey.UpArrow)
                {
                    if (index <= 0)
                    {
                        index = items.Count - 1;
                    }
                    else
                    {
                        index--;
                    }
                }
                else if (ckey.Key == ConsoleKey.Enter)
                {
                    return(items[index]);
                }
                Console.Clear();
                return("");
            }

            void Boundary()
            {
                leftBoundary   = new List <Position>();
                rightBoundary  = new List <Position>();
                bottomBoundary = new List <Position>();

                for (int i = 1; i < Console.WindowHeight - 1; i++)
                {
                    leftBoundary.Add(new Position(i, 0));
                }
                for (int i = 1; i < Console.WindowHeight - 1; i++)
                {
                    rightBoundary.Add(new Position(i, Console.WindowWidth - 1));
                }
                for (int i = 0; i < Console.WindowWidth - 1; i++)
                {
                    bottomBoundary.Add(new Position(Console.WindowHeight - 1, i));
                }
            }

            //main game loop
            void play()
            {
                PlayMusic("game");
                //initialises variables
                initialise();
                while (gameFlag)
                {
                    //hides cursor
                    Console.CursorVisible = false;
                    negativePoints++;
                    foreach (Position boundary in leftBoundary)
                    {
                        Draw(boundary, "▌", ConsoleColor.Green);
                    }
                    foreach (Position boundary in rightBoundary)
                    {
                        Draw(boundary, "▌", ConsoleColor.Green);
                    }
                    foreach (Position boundary in bottomBoundary)
                    {
                        Draw(boundary, "▀", ConsoleColor.Green);
                    }

                    //This draws the obstacles on the screen
                    foreach (Position obstacle in obstacles)
                    {
                        Draw(obstacle, "▒", ConsoleColor.Cyan);
                    }
                    //This draws the Nobstacles on the screen
                    foreach (Position Nobstacle in Nobstacles)
                    {
                        Draw(Nobstacle, "#", ConsoleColor.Red);
                    }
                    //Draws the snake on the console
                    foreach (Position position in snakeElements)
                    {
                        Draw(position, "*", ConsoleColor.DarkGray);
                    }
                    //Draws the food,trap,reward on the console
                    Draw(food, "♥♥", ConsoleColor.Yellow);
                    Draw(trap, "♥♥", ConsoleColor.DarkYellow);
                    Draw(reward, "♥♥", ConsoleColor.DarkYellow);
                    if (foodCounter >= 5)
                    {
                        Draw(specialFood, "&", ConsoleColor.Green);
                    }

                    //checks if user can input values through keyboard
                    if (Console.KeyAvailable)
                    {
                        //The controls of the snake
                        ConsoleKeyInfo userInput = Console.ReadKey(true);
                        snakeMove(userInput);
                    }

                    //return the last element in the snakebody
                    snakeHead = snakeElements.Last();
                    //sets the direction the snake will move
                    nextDirection = directions[direction];

                    //changes the direction of the snakehead when the snake direction changes
                    snakeNewHead = new Position(snakeHead.row + nextDirection.row,
                                                snakeHead.col + nextDirection.col);

                    //allows the snake to exit the window and enter at the opposite side
                    snakeExitScreen();

                    //user points calculation
                    calculatePoints();

                    //displays points while playing game
                    displayPoints();

                    userLives();

                    //checks snake collision with obstacles and Nobstacles and ends the game
                    if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                    {
                        Console.Beep(3000, 1000);
                        remainingLives--;
                        if (remainingLives < 0)
                        {
                            endGame("lose");
                            restart();
                        }
                    }
                    //checks snake collision with obstacles and Nobstacles and ends the game
                    if (Nobstacles.Contains(snakeNewHead))
                    {
                        Console.Beep(2000, 1500);
                        remainingLives = remainingLives - 1;
                        if (remainingLives <= 0)
                        {
                            endGame("lose");
                            restart();
                        }
                    }

                    //winning game logic
                    if (userPoints >= 1000)
                    {
                        endGame("win");
                        restart();
                    }

                    //sets the last element in the queue to be *
                    Draw(snakeHead, "*", ConsoleColor.DarkGray);

                    //sets the snake head by adding < and changing its direction depending on the direction the snake is moving
                    //inside the queue as first element
                    snakeElements.Enqueue(snakeNewHead);
                    //contains logic for snake movement
                    snakeMoves();



                    //game main logic//
                    //Snake eating on the food @ or is moving
                    if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                    {
                        Console.Beep();
                        // spawns new food at a random position if the snake ate the food

                        do
                        {
                            food = newRandomPosition(windowHeight, windowWidth);
                        }while (snakeElements.Contains(food) || obstacles.Contains(food) || Nobstacles.Contains(food));
                        lastFoodTime = Environment.TickCount;
                        Draw(food, "♥♥", ConsoleColor.Yellow);
                        foodCounter++;
                        sleepTime--;

                        //spawns obstacles and ensures the obstacle do not spawn on food

                        Position obstacle;
                        do
                        {
                            obstacle = newRandomPosition(windowHeight, windowWidth);
                        }while (snakeElements.Contains(obstacle) || obstacles.Contains(obstacle) || (food.row != obstacle.row && food.col != obstacle.row));
                        //adds obstacle in the list of obstacles and draw the obstacle
                        obstacles.Add(obstacle);
                        Draw(obstacle, "▒", ConsoleColor.Cyan);

                        //spawns Nobstacles and ensures the Nobstacle do not spawn on food
                        Position Nobstacle;
                        do
                        {
                            Nobstacle = newRandomPosition(windowHeight, windowWidth);
                        }while (snakeElements.Contains(Nobstacle) || Nobstacles.Contains(Nobstacle) || (food.row != Nobstacle.row && food.col != Nobstacle.row));
                        //adds obstacle in the list of obstacles and draw the obstacle
                        Nobstacles.Add(Nobstacle);
                        Draw(Nobstacle, "#", ConsoleColor.Red);
                    }
                    else if (snakeNewHead.col == specialFood.col && snakeNewHead.row == specialFood.row)
                    {
                        Console.Beep();
                        foodCounter = 0;
                        specialFoodCounter++;
                        do
                        {
                            specialFood = newRandomPosition(windowHeight, windowWidth);
                        } while (snakeElements.Contains(specialFood) || obstacles.Contains(specialFood) || Nobstacles.Contains(specialFood));
                        Draw(specialFood, "   ");
                    }
                    else if (snakeNewHead.col == trap.col && snakeNewHead.row == trap.row)
                    {
                        Console.Beep();
                        remainingLives = remainingLives - 1;
                        Draw(reward, "  ");
                        do
                        {
                            trap   = newRandomPosition(windowHeight, windowWidth);
                            reward = newRandomPosition(windowHeight, windowWidth);
                        } while (snakeElements.Contains(trap) || obstacles.Contains(trap) || Nobstacles.Contains(trap));
                        Draw(trap, "♥♥", ConsoleColor.DarkYellow);
                        Draw(reward, "♥♥", ConsoleColor.DarkYellow);
                        if (remainingLives <= 0)
                        {
                            endGame("lose");
                            restart();
                        }
                    }
                    else if (snakeNewHead.col == reward.col && snakeNewHead.row == reward.row)
                    {
                        Console.Beep();
                        remainingLives = remainingLives + 1;
                        Draw(trap, "  ");
                        do
                        {
                            trap   = newRandomPosition(windowHeight, windowWidth);
                            reward = newRandomPosition(windowHeight, windowWidth);
                        } while (snakeElements.Contains(reward) || obstacles.Contains(reward) || Nobstacles.Contains(reward));
                        Draw(trap, "♥♥", ConsoleColor.DarkYellow);
                        Draw(reward, "♥♥", ConsoleColor.DarkYellow);
                    }
                    else
                    {
                        //dequeue removes the first element added in the queue and returns it
                        //
                        // moving...
                        Position last = snakeElements.Dequeue();
                        Draw(last, " ");
                    }



                    //dispawns the food and spawns it on another place
                    //if the snake does not eat food before it despawns the user points are penalised by increasing the negative points
                    if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                    {
                        negativePoints += 10;
                        Draw(food, " ");
                        do
                        {
                            food = newRandomPosition(windowHeight, windowWidth);
                        }while (snakeElements.Contains(food) || obstacles.Contains(food) || Nobstacles.Contains(food));
                        lastFoodTime = Environment.TickCount;
                    }
                    Draw(food, "♥♥", ConsoleColor.Yellow);
                    sleepTime -= 0.01;

                    Thread.Sleep((int)sleepTime);
                }
            }

            //FUNCTIONS USED IN PLAY (CONTAINS GAME LOGIC)

            //changes direction of snake
            void snakeMove(ConsoleKeyInfo key)
            {
                if (key.Key == ConsoleKey.LeftArrow)
                {
                    if (direction != right)
                    {
                        direction = left;
                    }
                }
                if (key.Key == ConsoleKey.RightArrow)
                {
                    if (direction != left)
                    {
                        direction = right;
                    }
                }
                if (key.Key == ConsoleKey.UpArrow)
                {
                    if (direction != down)
                    {
                        direction = up;
                    }
                }
                if (key.Key == ConsoleKey.DownArrow)
                {
                    if (direction != up)
                    {
                        direction = down;
                    }
                }
            }

            //moves snake logic
            void snakeMoves()
            {
                if (direction == right)
                {
                    Draw(snakeNewHead, ">", ConsoleColor.Gray);
                }
                ;
                if (direction == left)
                {
                    Draw(snakeNewHead, "<", ConsoleColor.Gray);
                }
                ;
                if (direction == up)
                {
                    Draw(snakeNewHead, "^", ConsoleColor.Gray);
                }
                ;
                if (direction == down)
                {
                    Draw(snakeNewHead, "v", ConsoleColor.Gray);
                }
                ;
            }

            //added boundary
            void snakeExitScreen()
            {
                if (snakeNewHead.col <= 1)
                {
                    snakeNewHead.col = Console.WindowWidth - 2;
                }
                if (snakeNewHead.row <= 0)
                {
                    snakeNewHead.row = Console.WindowHeight - 2;
                }
                if (snakeNewHead.row >= Console.WindowHeight - 1)
                {
                    snakeNewHead.row = 1;
                }
                if (snakeNewHead.col >= Console.WindowWidth - 1)
                {
                    snakeNewHead.col = 2;
                }
            }

            void calculatePoints()
            {
                userPoints  = (snakeElements.Count - 4) * 100 - negativePoints;
                userPoints += specialFoodCounter * 300;
                if (userPoints < 0)
                {
                    userPoints = 0;
                }
                userPoints = Math.Max(userPoints, 0);
            }

            //displays the user points during gameplay
            void displayPoints()
            {
                string   displaypoints  = $" Points:{userPoints}";
                int      pos            = Console.WindowWidth - displaypoints.Length;
                Position pointsPosition = new Position(0, pos);

                Draw(pointsPosition, displaypoints);
            }

            //display remaining lives during gameplay
            void userLives()
            {
                string   displaylives  = $" Lives:{remainingLives}";
                int      pos           = Console.WindowWidth - (displaylives.Length + 20);
                Position livesPosition = new Position(0, pos);

                Draw(livesPosition, displaylives);
            }

            //METHODS HANDLING END GAME

            //displays ending screen depending on outcome
            void endGame(string outcome)
            {
                if (userPoints > highScoreValue)
                {
                    highScoreValue = userPoints;
                }
                string   points          = $"Your points are: {userPoints}";
                string   highScoreString = $"High Score: {highScoreValue}";
                string   congratulation  = $"Congratulations {username} !!! You Win !!!";
                string   lose            = $"Game Over! {username}";
                Position gameOver        = new Position((Console.WindowHeight - 1) / 2, ((Console.WindowWidth - 1) / 2) - points.Length / 2);
                Position pointsPos       = new Position(((Console.WindowHeight - 1) / 2) + 1, ((Console.WindowWidth - 1) / 2) - points.Length / 2);
                Position scorePos        = new Position(((Console.WindowHeight - 1) / 2) + 2, ((Console.WindowWidth - 1) / 2) - points.Length / 2);

                if (outcome == "win")
                {
                    PlayMusic("main");
                    Draw(gameOver, congratulation, ConsoleColor.Green);
                    Draw(pointsPos, points, ConsoleColor.Green);
                    Draw(scorePos, highScoreString, ConsoleColor.Green);
                    Console.WriteLine("\n");
                    storeValues(userPoints, username, highScoreValue);
                }
                else if (outcome == "lose")
                {
                    PlayMusic("main");
                    Draw(gameOver, lose, ConsoleColor.Red);
                    Draw(pointsPos, points, ConsoleColor.Red);
                    Draw(scorePos, highScoreString, ConsoleColor.Red);
                    storeValues(userPoints, username, highScoreValue);
                }

                if (username != "")
                {
                    scoreboard.Insert(0, $"Username: {username} , Score: {userPoints}");
                }
            }

            //restarts the game
            void restart()
            {
                Console.ReadKey();
                gameFlag = false;
                menuFlag = true;
                menu();
            }

            //DATA HANDLING METHODS

            //for writing users and their points earned
            void storeValues(int points, string user, int hs)
            {
                if (user.Length > 0)
                {
                    if (points > userExists(user))
                    {
                        var us = File.Open($"..\\..\\{user}.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                        using (StreamWriter sw = new StreamWriter(us))
                        {
                            {
                                sw.WriteLine($"{points}");
                                sw.Close();
                            }
                        }
                    }
                    var fhs = File.Open("..\\..\\highScore.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    using (StreamWriter sw = new StreamWriter(fhs))
                    {
                        sw.WriteLine(hs);
                        sw.Close();
                    }
                }
            }

            //checks if user exists and returns their previous score or else returns 0;
            int userExists(string user)
            {
                if (File.Exists($"..\\..\\{user}.txt"))
                {
                    FileStream userfile = File.Open($"..\\..\\{user}.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    using (StreamReader sr = new StreamReader(userfile))
                    {
                        string highscore = sr.ReadLine();
                        if (highscore != null)
                        {
                            highscore.Trim();
                            sr.Close();
                            return(Int32.Parse(highscore));
                        }
                        else
                        {
                            sr.Close();
                            return(0);
                        }
                    }
                }
                return(0);
            }

            //stores highscore in a text file
            int highScore()
            {
                var fs = File.Open("..\\..\\highScore.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);

                using (StreamReader sr = new StreamReader(fs))
                {
                    string highscore = sr.ReadLine();
                    if (highscore != null)
                    {
                        highscore.Trim();
                        sr.Close();
                        return(Int32.Parse(highscore));
                    }
                    else
                    {
                        sr.Close();
                        return(0);
                    }
                }
            }
        }
Exemplo n.º 4
0
        private static void Main(string[] args)
        {
            byte b    = 0;
            byte b2   = 1;
            byte b3   = 2;
            byte b4   = 3;
            int  num  = 0;
            int  num2 = 8000;
            int  num3 = 0;

            Position[] array = new Position[4]
            {
                new Position(0, 1),
                new Position(0, -1),
                new Position(1, 0),
                new Position(-1, 0)
            };
            double num4   = 100.0;
            int    num5   = b;
            Random random = new Random();

            Console.BufferHeight = Console.WindowHeight;
            num = Environment.TickCount;
            List <Position> list = new List <Position>
            {
                new Position(12, 12),
                new Position(14, 20),
                new Position(7, 7),
                new Position(19, 19),
                new Position(6, 9)
            };

            foreach (Position item3 in list)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.SetCursorPosition(item3.col, item3.row);
                Console.Write("=");
            }
            Queue <Position> queue = new Queue <Position>();

            for (int i = 0; i <= 5; i++)
            {
                queue.Enqueue(new Position(0, i));
            }
            Position item;

            do
            {
                item = new Position(random.Next(0, Console.WindowHeight), random.Next(0, Console.WindowWidth));
            }while (queue.Contains(item) || list.Contains(item));
            Console.SetCursorPosition(item.col, item.row);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("@");
            foreach (Position item4 in queue)
            {
                Console.SetCursorPosition(item4.col, item4.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");
            }
            while (true)
            {
                num3++;
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo consoleKeyInfo = Console.ReadKey();
                    if (consoleKeyInfo.Key == ConsoleKey.LeftArrow && num5 != b)
                    {
                        num5 = b2;
                    }
                    if (consoleKeyInfo.Key == ConsoleKey.RightArrow && num5 != b2)
                    {
                        num5 = b;
                    }
                    if (consoleKeyInfo.Key == ConsoleKey.UpArrow && num5 != b3)
                    {
                        num5 = b4;
                    }
                    if (consoleKeyInfo.Key == ConsoleKey.DownArrow && num5 != b4)
                    {
                        num5 = b3;
                    }
                }
                Position position  = queue.Last();
                Position position2 = array[num5];
                Position item2     = new Position(position.row + position2.row, position.col + position2.col);
                if (item2.col < 0)
                {
                    item2.col = Console.WindowWidth - 1;
                }
                if (item2.row < 0)
                {
                    item2.row = Console.WindowHeight - 1;
                }
                if (item2.row >= Console.WindowHeight)
                {
                    item2.row = 0;
                }
                if (item2.col >= Console.WindowWidth)
                {
                    item2.col = 0;
                }
                if (queue.Contains(item2) || list.Contains(item2))
                {
                    break;
                }
                Console.SetCursorPosition(position.col, position.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");
                queue.Enqueue(item2);
                Console.SetCursorPosition(item2.col, item2.row);
                Console.ForegroundColor = ConsoleColor.Gray;
                if (num5 == b)
                {
                    Console.Write(">");
                }
                if (num5 == b2)
                {
                    Console.Write("<");
                }
                if (num5 == b4)
                {
                    Console.Write("^");
                }
                if (num5 == b3)
                {
                    Console.Write("v");
                }
                if (item2.col == item.col && item2.row == item.row)
                {
                    do
                    {
                        item = new Position(random.Next(0, Console.WindowHeight), random.Next(0, Console.WindowWidth));
                    }while (queue.Contains(item) || list.Contains(item));
                    num = Environment.TickCount;
                    Console.SetCursorPosition(item.col, item.row);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("@");
                    num4 -= 1.0;
                    Position position3 = default(Position);
                    do
                    {
                        position3 = new Position(random.Next(0, Console.WindowHeight), random.Next(0, Console.WindowWidth));
                    }while (queue.Contains(position3) || list.Contains(position3) || (item.row != position3.row && item.col != position3.row));
                    list.Add(position3);
                    Console.SetCursorPosition(position3.col, position3.row);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("=");
                }
                else
                {
                    Position position4 = queue.Dequeue();
                    Console.SetCursorPosition(position4.col, position4.row);
                    Console.Write(" ");
                }
                if (Environment.TickCount - num >= num2)
                {
                    num3 += 50;
                    Console.SetCursorPosition(item.col, item.row);
                    Console.Write(" ");
                    do
                    {
                        item = new Position(random.Next(0, Console.WindowHeight), random.Next(0, Console.WindowWidth));
                    }while (queue.Contains(item) || list.Contains(item));
                    num = Environment.TickCount;
                }
                Console.SetCursorPosition(item.col, item.row);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("@");
                num4 -= 0.01;
                Thread.Sleep((int)num4);
            }
            Console.SetCursorPosition(0, 0);
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Game over!");
            int val = (queue.Count - 6) * 100 - num3;

            val = Math.Max(val, 0);
            Console.WriteLine("Your points are: {0}", val);
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            string name;

            do
            {
                Console.Write("What is your name with 10 character: ");                //Prompt for the player's name
                name = Console.ReadLine();
            } while (name == "" || name.Length > 10);


            Console.Clear();

            byte right                 = 0;       //Define the direction of right of snake
            byte left                  = 1;       //Define the direction of left of snake
            byte down                  = 2;       //Define the direction of down of snake
            byte up                    = 3;       //Define the direction of up of snake
            int  lastFoodTime          = 0;       //Define the life time of the food
            int  foodDissapearTime     = 20000;   //Define the disappear time of the food to 20 seconds which made the food disappears slower
            int  negativePoints        = 0;       //Define the score need to be minus if food disappear
            int  snakebody_size_origin = 3;       //Define the initial length of snake
            int  win_score             = 500;     //Define the score of winning

            int lastspecialFoodTime      = 0;     //Define the life time of the special food
            int specialfoodDissapearTime = 10000; //Define the disappear time of the special food to 10 seconds which made the food disappears slower

            int increment_length = 0;

            bool specialfoodflag = false;               //fix the specialfood cannot eating 2 times;

            int life = 3;

            int current_level = 1;

            //create object
            SoundPlayer back_player     = new SoundPlayer("Snakesongv2.wav");
            SoundPlayer eat_player      = new SoundPlayer("eat.wav");
            SoundPlayer gameover_player = new SoundPlayer("gameover.wav");
            SoundPlayer win_player      = new SoundPlayer("win.wav");

            //play blackground music by looping
            back_player.PlayLooping();

            //Create an array of the coordinates
            Position[] directions = new Position[]
            {
                new Position(0, 1),                 // right
                new Position(0, -1),                // left
                new Position(1, 0),                 // down
                new Position(-1, 0),                // up
            };

            double sleepTime = 100;                       //Define the speed of the sname
            double nextspeed = sleepTime;
            int    direction = right;                     //Define the moving direction of the snake  at beginning
            Random randomNumbersGenerator = new Random(); //Define the random number generator

            Console.BufferHeight = Console.WindowHeight;  //Set the screen size of the game to the console size
            lastFoodTime         = Environment.TickCount; //Set the timer of the food
            lastspecialFoodTime  = Environment.TickCount; //Set the timer of the food

            //Initialize the length of the "snake tail"
            Queue <Position> snakeElements = new Queue <Position>();

            for (int i = 0; i <= snakebody_size_origin; i++)
            {
                snakeElements.Enqueue(new Position(1, i));
            }

            //Initialize the position of the obstacles
            List <Position> obstacles = new List <Position>();

            for (int i = 0; i < 5; ++i)
            {
                Position obstacle;
                do
                {
                    obstacle = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth - 2));  //define a random place the obstacle into the game field
                }while (snakeElements.Contains(obstacle) ||
                        obstacles.Contains(obstacle));
                obstacles.Add(obstacle);
            }

            foreach (Position obstacle in obstacles)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.SetCursorPosition(obstacle.col, obstacle.row);
                Console.Write("\u2593");
            }

            //position of the food
            Position food;

            //randomize the position of the food
            do
            {
                food = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                    randomNumbersGenerator.Next(0, Console.WindowWidth - 3));
            }
            //while the snake or the obstacles touches the food, its position will always changed
            while (snakeElements.Contains(food) || obstacles.Contains(food));
            Console.SetCursorPosition(food.col, food.row);            //set the column and row position of the food
            Console.ForegroundColor = ConsoleColor.Yellow;            //set the foreground color to yellow
            Console.Write("\u2665\u2665");

            //position of the special food
            Position specialfood;

            specialfoodflag = true;
            //randomize the position of the special food
            do
            {
                specialfood = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                           randomNumbersGenerator.Next(0, Console.WindowWidth - 2));
            }
            //while the snake or the obstacles touches the food, its position will always changed
            while (snakeElements.Contains(specialfood) || obstacles.Contains(specialfood) || (food.row == specialfood.row && food.col == specialfood.col));
            Console.SetCursorPosition(specialfood.col, specialfood.row); //set the column and row position of the food
            Console.ForegroundColor = ConsoleColor.Yellow;               //set the foreground color to yellow
            Console.Write("\u2736");

            foreach (Position position in snakeElements)
            {
                Console.SetCursorPosition(position.col, position.row); //set the column and row position of snake elements
                Console.ForegroundColor = ConsoleColor.DarkGray;       //set the foreground color to dark grey
                Console.Write("*");                                    //this is the body of snake
            }

            while (true)
            {
                negativePoints++;

                if (Console.KeyAvailable)                       //To gets a value indicating whether a key press is available in the input stream.
                {
                    ConsoleKeyInfo userInput = Console.ReadKey(true);
                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        if (direction != right)
                        {
                            direction = left;
                        }
                    }
                    if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        if (direction != left)
                        {
                            direction = right;
                        }
                    }
                    if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        if (direction != down)
                        {
                            direction = up;
                        }
                    }
                    if (userInput.Key == ConsoleKey.DownArrow)
                    {
                        if (direction != up)
                        {
                            direction = down;
                        }
                    }
                }

                Position snakeHead     = snakeElements.Last();            //Set the head of the snake to the last item of the body
                Position nextDirection = directions[direction];           //Define the next direction of snake move after user enter the arrow key

                Position snakeNewHead = new Position(snakeHead.row + nextDirection.row,
                                                     snakeHead.col + nextDirection.col);//Set the next body movind direction to the head of snake

                if (snakeNewHead.col < 0)
                {
                    snakeNewHead.col = Console.WindowWidth - 2;                                      //if the snake head hit the left wall, the snake will pass through it and appear on the right wall
                }
                if (snakeNewHead.row < 1)
                {
                    snakeNewHead.row = Console.WindowHeight - 1;                                      //if the snake head hit the top wall, the snake will pass through it and appear on the bottom wall
                }
                if (snakeNewHead.row >= Console.WindowHeight)
                {
                    snakeNewHead.row = 1;                                                          //if the snake head hit the bottom wall, the snake will pass through it and appear on the top wall
                }
                if (snakeNewHead.col >= Console.WindowWidth - 1)
                {
                    snakeNewHead.col = 0;                                                                                        //if the snake head hit the right wall, the snake will pass through it and appear on the left wall
                }
                int current_score = (snakeElements.Count - increment_length - snakebody_size_origin - 1) * 100 - negativePoints; //Calculate the score of the player
                current_score = Math.Max(current_score, 0) - 1;                                                                  //round the score to int

                if (current_score < 0)                                                                                           //if score less than 0, score equal 0
                {
                    current_score = 0;
                }
                string score_title = "Score: ";
                Console.SetCursorPosition((Console.WindowWidth - score_title.Length - 4), 0); //Set position to top right corner
                Console.ForegroundColor = ConsoleColor.Red;                                   //Set the font color to red
                Console.Write(score_title + current_score.ToString().PadLeft(4, '0'));        //Display the text

                string level_title = "Level: ";
                Console.SetCursorPosition(0, 0);
                Console.ForegroundColor = ConsoleColor.Red;                            //Set the font color to red
                Console.Write(level_title + current_level.ToString().PadLeft(3, '0')); //Display the text

                string win_title = "Next level Score: ";
                Console.SetCursorPosition(20, 0);                                //Set position to top right corner
                Console.ForegroundColor = ConsoleColor.Red;                      //Set the font color to red
                Console.Write(win_title + win_score.ToString().PadLeft(3, '0')); //Display the text


                string length_title = "Size: ";
                Console.SetCursorPosition(50, 0);                                             //Set position to top right corner
                Console.ForegroundColor = ConsoleColor.Red;                                   //Set the font color to red
                Console.Write(length_title + snakeElements.Count.ToString().PadLeft(3, '0')); //Display the text


                string negative_title = "Speed: ";
                Console.SetCursorPosition(70, 0);                                                                 //Set position to top right corner
                Console.ForegroundColor = ConsoleColor.Red;                                                       //Set the font color to red
                Console.Write(negative_title + Math.Abs(Math.Round(sleepTime) - 100).ToString().PadLeft(3, '0')); //Display the text


                string life_title = "Life: ";
                Console.SetCursorPosition(90, 0);
                Console.ForegroundColor = ConsoleColor.Red;                  //Set the font color to red
                Console.Write(life_title + life.ToString().PadLeft(3, '0')); //Display the text

                //winning requirement
                if (current_score / win_score > 0 && current_score > 0)
                {
                    increment_length += 1;
                    int currentlength = snakeElements.Count - increment_length;
                    current_level += 1;
                    negativePoints = 0;
                    win_score     += 100;
                    if (sleepTime <= 10)
                    {
                        sleepTime = 10;
                    }
                    else
                    {
                        nextspeed -= 10;
                        sleepTime  = nextspeed;
                    }
                    foodDissapearTime -= 100;
                    for (int i = 1; i < (currentlength - snakebody_size_origin); ++i)
                    {
                        Position last = snakeElements.Dequeue();       //Define the last position of the snake body
                        Console.SetCursorPosition(last.col, last.row); //Get the curser of that position
                        Console.Write(" ");                            //Display space at that field
                    }
                    foreach (Position obstacle in obstacles)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.SetCursorPosition(obstacle.col, obstacle.row);
                        Console.Write(" ");
                    }

                    obstacles.Clear();

                    for (int i = 0; i < 5; ++i)
                    {
                        Position obstacle;
                        do
                        {
                            obstacle = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                                    randomNumbersGenerator.Next(0, Console.WindowWidth - 2));          //define a random place the obstacle into the game field
                        }while (snakeElements.Contains(obstacle) ||
                                obstacles.Contains(obstacle));
                        obstacles.Add(obstacle);
                    }

                    foreach (Position obstacle in obstacles)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.SetCursorPosition(obstacle.col, obstacle.row);
                        Console.Write("\u2593");
                    }

                    //randomize the position of the special food
                    specialfoodflag = true;
                    do
                    {
                        specialfood = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                                   randomNumbersGenerator.Next(0, Console.WindowWidth - 2));
                    }
                    //while the snake or the obstacles touches the food, its position will always changed
                    while (snakeElements.Contains(specialfood) || obstacles.Contains(specialfood) || (food.row == specialfood.row && food.col == specialfood.col));
                    Console.SetCursorPosition(specialfood.col, specialfood.row);      //set the column and row position of the food
                    Console.ForegroundColor = ConsoleColor.Yellow;                    //set the foreground color to yellow
                    Console.Write("\u2736");

                    lastspecialFoodTime = Environment.TickCount;                    //gets the millisecond count from the computer's system timer
                }

                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))                //if the head of the snake hit the body of snake or obstacle
                {
                    if (life > 0)
                    {
                        life -= 1;

                        List <Position> tempobstacles = new List <Position>();
                        foreach (Position obstacle in obstacles)
                        {
                            if (!(obstacle.col == snakeNewHead.col && obstacle.row == snakeNewHead.row))
                            {
                                tempobstacles.Add(obstacle);
                            }
                        }

                        obstacles.Clear();
                        foreach (Position obstacle in tempobstacles)
                        {
                            obstacles.Add(obstacle);
                        }

                        Position last = snakeElements.Dequeue();       //Define the last position of the snake body
                        Console.SetCursorPosition(last.col, last.row); //Get the curser of that position
                        Console.Write(" ");                            //Display space at that field
                    }
                    else
                    {
                        gameover_player.Play();
                        string msg       = "Game over!";                                                               //Game over message
                        string level_msg = "Your level are: " + current_level;                                         //Current level message
                        string score_msg = "Your points are: " + current_score;                                        //Current score message
                        string exit_msg  = "Press enter to exit the game.";                                            //Exit message
                        Console.SetCursorPosition((Console.WindowWidth - msg.Length) / 2, (Console.WindowHeight / 2)); //Set the cursor position to the beginning
                        Console.ForegroundColor = ConsoleColor.Red;                                                    //Set the font color to red
                        Console.WriteLine(msg);                                                                        //Display the text
                        Console.SetCursorPosition((Console.WindowWidth - level_msg.Length) / 2, (Console.WindowHeight / 2) + 1);
                        Console.Write(level_msg);                                                                      //Display the score
                        Console.SetCursorPosition((Console.WindowWidth - score_msg.Length) / 2, (Console.WindowHeight / 2) + 2);
                        Console.Write(score_msg);                                                                      //Display the score
                        Console.SetCursorPosition((Console.WindowWidth - exit_msg.Length) / 2, (Console.WindowHeight / 2) + 3);
                        Console.Write(exit_msg);                                                                       //Display the exit message
                        string fullPath = Directory.GetCurrentDirectory() + "/score.txt";

                        int finalscore = 0;
                        for (int index = 2; index <= current_level; ++index)
                        {
                            finalscore += ((index - 2) * 100) + 500;
                        }
                        finalscore += current_score;

                        if (!File.Exists(fullPath))
                        {
                            using (StreamWriter writer = new StreamWriter(fullPath))
                            {
                                writer.WriteLine(name + " " + current_level.ToString().PadLeft(2, '0') + " " + current_score.ToString().PadLeft(3, '0') + " " + finalscore.ToString().PadLeft(3, '0'));
                            }
                        }
                        else
                        {
                            using (StreamWriter writer = File.AppendText(fullPath))
                            {
                                writer.WriteLine(name + " " + current_level.ToString().PadLeft(2, '0') + " " + current_score.ToString().PadLeft(3, '0') + " " + finalscore.ToString().PadLeft(3, '0'));
                            }
                        }

                        int count;

                        count = File.ReadLines(fullPath).Count();

                        string[,] arr = new string[count, 4];
                        int j;
                        using (StreamReader sr = File.OpenText(fullPath))
                        {
                            string s = "";
                            count = 0;
                            while ((s = sr.ReadLine()) != null)
                            {
                                string[] data = s.Split(' ');
                                j = 0;
                                foreach (string d in data)
                                {
                                    arr[count, j] = d;
                                    j            += 1;
                                }
                                count += 1;
                            }
                        }

                        for (int i = 0; i < arr.GetLength(0) - 1; i++)
                        {
                            for (j = i; j < arr.GetLength(0); j++)
                            {
                                if (int.Parse(arr[i, 3]) < int.Parse(arr[j, 3]))                                 // sort by descending by first index of each row
                                {
                                    for (int k = 0; k < arr.GetLength(1); k++)
                                    {
                                        var temp = arr[i, k];
                                        arr[i, k] = arr[j, k];
                                        arr[j, k] = temp;
                                    }
                                }
                            }
                        }

                        string rank_title = "     Name | Rank | Level | Score";
                        Console.SetCursorPosition((Console.WindowWidth - rank_title.Length) / 2, (Console.WindowHeight / 2) + 4);
                        Console.WriteLine(rank_title);

                        for (int i = 0; i < count; ++i)
                        {
                            if (i < 5)
                            {
                                string record_msg = String.Format("{0,10} | {1,4} | {2,5} | {3,5}", arr[i, 0], (i + 1), arr[i, 1], arr[i, 3]);
                                Console.SetCursorPosition((Console.WindowWidth - record_msg.Length) / 2, (Console.WindowHeight / 2) + 5 + i);
                                Console.Write(record_msg);
                            }
                            else
                            {
                                continue;
                            }
                        }
                        Console.ReadKey(true);
                        return;
                    }
                }

                Console.SetCursorPosition(snakeHead.col, snakeHead.row); //set the column and row position of the snake head
                Console.ForegroundColor = ConsoleColor.DarkGray;         //set the foreground color to dark grey
                Console.Write("*");                                      //this is the body of snake

                snakeElements.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                Console.ForegroundColor = ConsoleColor.Gray;
                if (direction == right)
                {
                    Console.Write(">");                                    //the snake head turns right
                }
                if (direction == left)
                {
                    Console.Write("<");                                   //the snake head turns left
                }
                if (direction == up)
                {
                    Console.Write("^");                                 //the snake head turns up
                }
                if (direction == down)
                {
                    Console.Write("v");                                   //the snake head turns down
                }
                if (snakeNewHead.col == specialfood.col && snakeNewHead.row == specialfood.row && (Environment.TickCount - lastspecialFoodTime) < specialfoodDissapearTime && specialfoodflag == true)
                {
                    eat_player.PlaySync();
                    back_player.PlayLooping();
                    specialfoodflag = false;
                    life           += 1;
                    for (int i = 0; i < (snakebody_size_origin + current_level) - 1; ++i)
                    {
                        Console.SetCursorPosition(snakeHead.col, snakeHead.row); //set the column and row position of the snake head
                        Console.ForegroundColor = ConsoleColor.DarkGray;         //set the foreground color to dark grey
                        Console.Write("*");                                      //this is the body of snake
                        snakeElements.Enqueue(snakeNewHead);
                        Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                        Console.ForegroundColor = ConsoleColor.Gray;
                    }
                }

                if ((snakeNewHead.col == food.col && snakeNewHead.row == food.row) || (snakeNewHead.col == food.col + 1 && snakeNewHead.row == food.row))
                {
                    if (snakeNewHead.col == food.col)
                    {
                        Console.SetCursorPosition(food.col + 1, food.row);
                        Console.Write(" ");
                    }
                    if (snakeNewHead.col == food.col + 1)
                    {
                        Console.SetCursorPosition(food.col, food.row);
                        Console.Write(" ");
                    }

                    eat_player.PlaySync();

                    back_player.PlayLooping();
                    // feeding the snake

                    Position obstacle = new Position();                    //Define a obstacle	position
                    do
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                                randomNumbersGenerator.Next(0, Console.WindowWidth - 2));      //define a random place the obstacle into the game field
                    }while (snakeElements.Contains(obstacle) ||
                            obstacles.Contains(obstacle) ||
                            (food.row == obstacle.row && food.col == obstacle.row)); //Redo if the position consist the location without snake body, food and existing obstacle
                    obstacles.Add(obstacle);                                         //Add the obstacle to its array
                    Console.SetCursorPosition(obstacle.col, obstacle.row);           //set the cursor to that position
                    Console.ForegroundColor = ConsoleColor.Cyan;                     //set the font color to cyan
                    Console.Write("\u2593");                                         //write the obstacle to the screen

                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth - 3));           //define a random place the food into the game field
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    lastFoodTime = Environment.TickCount;
                    Console.SetCursorPosition(food.col, food.row);      //set the cursor to that position
                    Console.ForegroundColor = ConsoleColor.Yellow;      //set the color of food to Yellow
                    Console.Write("\u2665\u2665");                      //set the shape of food
                    if (sleepTime <= 10)
                    {
                        sleepTime = 10;
                    }
                    else
                    {
                        sleepTime--;
                    }
                }
                else
                {
                    // moving...
                    Position last = snakeElements.Dequeue();       //Define the last position of the snake body
                    Console.SetCursorPosition(last.col, last.row); //Get the curser of that position
                    Console.Write(" ");                            //Display space at that field
                }

                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints = negativePoints + 50;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write(" ");
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),     //randomize the window height of the food position
                                            randomNumbersGenerator.Next(0, Console.WindowWidth - 3)); //randomize the window width of the food position
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    lastFoodTime = Environment.TickCount;                                             //gets the millisecond count from the computer's system timer
                }

                if (Environment.TickCount - lastspecialFoodTime >= specialfoodDissapearTime)
                {
                    Console.SetCursorPosition(specialfood.col, specialfood.row);
                    Console.Write(" ");
                }

                Console.SetCursorPosition(food.col, food.row);                //set the food column and row position
                Console.ForegroundColor = ConsoleColor.Yellow;                //set the foreground color to yellow
                Console.Write("\u2665\u2665");

                if (snakeElements.Contains(specialfood))
                {
                    Console.SetCursorPosition(specialfood.col, specialfood.row);
                    Console.ForegroundColor = ConsoleColor.DarkGray; //set the foreground color to dark grey
                    Console.Write("*");                              //this is the body of snake
                }

                if (sleepTime <= 10)
                {
                    sleepTime = 10;
                }
                else
                {
                    sleepTime -= 0.01;                 //deducts the sleep time by 0.01
                }
                Thread.Sleep((int)sleepTime);          //suspends the current thread for the specified number of milliseconds
            }
        }
Exemplo n.º 6
0
        private static void Main(string[] args)
        {
            Position food;
            bool     flag;
            bool     flag1;
            bool     flag2;
            bool     flag3;
            byte     right             = 0;
            byte     left              = 1;
            byte     down              = 2;
            byte     up                = 3;
            int      lastFoodTime      = 0;
            int      foodDissapearTime = 0x1f40;
            int      negativePoints    = 0;

            Position[] directions             = new Position[] { new Position(0, 1), new Position(0, -1), new Position(1, 0), new Position(-1, 0) };
            double     sleepTime              = 100;
            int        direction              = right;
            Random     randomNumbersGenerator = new Random();

            Console.BufferHeight = Console.WindowHeight;
            lastFoodTime         = Environment.TickCount;
            List <Position> obstacles = new List <Position>()
            {
                new Position(12, 12),
                new Position(14, 20),
                new Position(7, 7),
                new Position(19, 19),
                new Position(6, 9)
            };

            foreach (Position obstacle in obstacles)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.SetCursorPosition(obstacle.col, obstacle.row);
                Console.Write("=");
            }
            Queue <Position> snakeElements = new Queue <Position>();

            for (int i = 0; i <= 5; i++)
            {
                snakeElements.Enqueue(new Position(0, i));
            }
            do
            {
                food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth));
                flag = (snakeElements.Contains(food) ? true : obstacles.Contains(food));
            }while (flag);
            Console.SetCursorPosition(food.col, food.row);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("@");
            foreach (Position position in snakeElements)
            {
                Console.SetCursorPosition(position.col, position.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");
            }
            while (true)
            {
                negativePoints++;
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userInput = Console.ReadKey();
                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        if (direction != right)
                        {
                            direction = left;
                        }
                    }
                    if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        if (direction != left)
                        {
                            direction = right;
                        }
                    }
                    if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        if (direction != down)
                        {
                            direction = up;
                        }
                    }
                    if (userInput.Key == ConsoleKey.DownArrow)
                    {
                        if (direction != up)
                        {
                            direction = down;
                        }
                    }
                }
                Position snakeHead     = snakeElements.Last <Position>();
                Position nextDirection = directions[direction];
                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;
                }
                if ((snakeElements.Contains(snakeNewHead) ? true : obstacles.Contains(snakeNewHead)))
                {
                    break;
                }
                Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");
                snakeElements.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                Console.ForegroundColor = ConsoleColor.Gray;
                if (direction == right)
                {
                    Console.Write(">");
                }
                if (direction == left)
                {
                    Console.Write("<");
                }
                if (direction == up)
                {
                    Console.Write("^");
                }
                if (direction == down)
                {
                    Console.Write("v");
                }
                if ((snakeNewHead.col != food.col ? true : snakeNewHead.row != food.row))
                {
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(" ");
                }
                else
                {
                    do
                    {
                        food  = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth));
                        flag2 = (snakeElements.Contains(food) ? true : obstacles.Contains(food));
                    }while (flag2);
                    lastFoodTime = Environment.TickCount;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("@");
                    sleepTime -= 1;
                    Position obstacle = new Position();
                    do
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth));
                        if (snakeElements.Contains(obstacle) || obstacles.Contains(obstacle))
                        {
                            flag3 = true;
                        }
                        else
                        {
                            flag3 = (food.row == obstacle.row ? false : food.col != obstacle.row);
                        }
                    }while (flag3);
                    obstacles.Add(obstacle);
                    Console.SetCursorPosition(obstacle.col, obstacle.row);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("=");
                }
                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints += 50;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write(" ");
                    do
                    {
                        food  = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth));
                        flag1 = (snakeElements.Contains(food) ? true : obstacles.Contains(food));
                    }while (flag1);
                    lastFoodTime = Environment.TickCount;
                }
                Console.SetCursorPosition(food.col, food.row);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("@");
                sleepTime -= 0.01;
                Thread.Sleep((int)sleepTime);
            }
            Console.SetCursorPosition(0, 0);
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Game over!");
            int userPoints = (snakeElements.Count - 6) * 100 - negativePoints;

            Console.WriteLine("Your points are: {0}", Math.Max(userPoints, 0));
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            byte right             = 0;
            byte left              = 1;
            byte down              = 2;
            byte up                = 3;
            int  lastFoodTime      = 0;
            int  foodDisappearTime = 8000;

            //Environment.TickCount()
            // DateTime.Now

            Position[] directions = new Position[]
            {
                new Position(0, 1),  // right
                new Position(0, -1), // left
                new Position(1, 0),  // down
                new Position(-1, 0), // up
            };

            double sleepTime = 100;
            int    direction = 0;
            Random randomNumbersGenerator = new Random();

            Console.BufferHeight = Console.WindowHeight;
            Position food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                         randomNumbersGenerator.Next(0, Console.WindowWidth));

            lastFoodTime = Environment.TickCount;
            Console.SetCursorPosition(food.col, food.row);
            Console.Write("@");

            Queue <Position> snakeElements = new Queue <Position>();

            for (int i = 0; i <= 5; i++)
            {
                snakeElements.Enqueue(new Position(0, i));
            }

            foreach (Position position in snakeElements)
            {
                Console.SetCursorPosition(position.col, position.row);
                Console.Write("*");
            }

            while (true)
            {
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userInput = Console.ReadKey();
                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        if (direction != right)
                        {
                            direction = left;
                        }
                    }
                    if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        if (direction != left)
                        {
                            direction = right;
                        }
                    }
                    if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        if (direction != down)
                        {
                            direction = up;
                        }
                    }
                    if (userInput.Key == ConsoleKey.DownArrow)
                    {
                        if (direction != up)
                        {
                            direction = down;
                        }
                    }
                }
                Position snakeHead     = snakeElements.Last();
                Position nextDirection = directions[direction];
                Position snakeNewHead  = new Position(snakeHead.row + nextDirection.row,
                                                      snakeHead.col + nextDirection.col);

                if (snakeNewHead.row < 0 ||
                    snakeNewHead.col < 0 ||
                    snakeNewHead.row >= Console.WindowHeight ||
                    snakeNewHead.col >= Console.WindowWidth ||
                    snakeElements.Contains(snakeNewHead))
                {
                    Console.SetCursorPosition(0, 0);
                    Console.WriteLine("Game over!");
                    Console.WriteLine("Your score is: {0}", (snakeElements.Count - 6) * 100);
                    return;
                }

                snakeElements.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                Console.Write("*");
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                {
                    // feeding the snake
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while(snakeElements.Contains(food));
                    lastFoodTime = Environment.TickCount;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write("@");
                    sleepTime--;
                }
                else
                {
                    // moving
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(" ");
                }

                if (Environment.TickCount - lastFoodTime >= foodDisappearTime)
                {
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write(" ");

                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while(snakeElements.Contains(food));
                    lastFoodTime = Environment.TickCount;
                }

                Console.SetCursorPosition(food.col, food.row);
                Console.Write("@");

                sleepTime -= 0.1;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 8
0
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



        static void Main(string[] args)
        {
            PlayMusic();
            //intialise different variable
            byte   right             = 0;
            byte   left              = 1;
            byte   down              = 2;
            byte   up                = 3;
            int    lastFoodTime      = 0;
            int    foodDissapearTime = 16000;
            int    negativePoints    = 0;
            string userName;

            Console.WriteLine("Enter your name: ");
            userName = Console.ReadLine();
            Console.Clear();
            Position[] directions = new Position[]
            {
                new Position(0, 1),  // right
                new Position(0, -1), // left
                new Position(1, 0),  // down
                new Position(-1, 0), // up
            };
            GameState state     = GameState.InMainMenu;
            Level     level     = Level.One;
            double    sleepTime = 100;
            int       direction = right;
            Random    randomNumbersGenerator = new Random();

            Console.BufferHeight = Console.WindowHeight;
            lastFoodTime         = Environment.TickCount;
            int lives = 3;

            while (true)
            {
                if (state == GameState.Start)
                {
                    Console.Clear();
                    List <Position> obstacles = MakeObstacles(randomNumbersGenerator);

                    //Declare a new variable snakeElements
                    Queue <Position> snakeElements = new Queue <Position>();
                    //Initialise the length of the snake
                    for (int i = 0; i <= 3; i++)
                    {
                        snakeElements.Enqueue(new Position(0, i));
                    }

                    // Creates new food at a random position (as long as the position has not been taken by an obstacles or the snake)

                    Position food = MakeFood(randomNumbersGenerator, obstacles, snakeElements, 0);

                    // Redraws the snake
                    foreach (Position position in snakeElements)
                    {
                        Console.SetCursorPosition(position.col, position.row);
                        Console.ForegroundColor = ConsoleColor.DarkGray;
                        Console.Write("*");
                    }

                    int  userPoints = 0;
                    int  time       = 0;
                    int  seconds    = 15;
                    bool mainloop   = true;
                    // Loops the game till it ends
                    while (mainloop)
                    {
                        int determiner = randomNumbersGenerator.Next(3);
                        userPoints = (snakeElements.Count - 4) * 100 - negativePoints;
                        Console.SetCursorPosition(0, 0);
                        Console.ForegroundColor = ConsoleColor.Cyan;

                        Console.WriteLine("Score: " + userPoints + " ");
                        Lives(lives);

                        time++;
                        if (time % 10 == 0)
                        {
                            seconds--;
                            if (seconds == -1)
                            {
                                seconds = 15;
                            }
                        }

                        Console.SetCursorPosition(0, 0);
                        Console.ForegroundColor = ConsoleColor.Green;
                        string thetimeTime = "Food time: ";
                        Console.WriteLine("\n");
                        Console.Write(new string(' ', (Console.WindowWidth - thetimeTime.Length) / 2));
                        Console.WriteLine(thetimeTime + seconds + " ");



                        level = WinCondition(userName, userPoints, level);

                        // Increment 1
                        negativePoints++;

                        // Detects key inputs to change direction
                        if (Console.KeyAvailable)
                        {
                            ConsoleKeyInfo userInput = Console.ReadKey();
                            if (userInput.Key == ConsoleKey.LeftArrow)
                            {
                                if (direction != right)
                                {
                                    direction = left;
                                }
                            }
                            if (userInput.Key == ConsoleKey.RightArrow)
                            {
                                if (direction != left)
                                {
                                    direction = right;
                                }
                            }
                            if (userInput.Key == ConsoleKey.UpArrow)
                            {
                                if (direction != down)
                                {
                                    direction = up;
                                }
                            }
                            if (userInput.Key == ConsoleKey.DownArrow)
                            {
                                if (direction != up)
                                {
                                    direction = down;
                                }
                            }
                        }

                        Position snakeHead     = snakeElements.Last();  // Sets the last element of the snake as the snake head
                        Position nextDirection = directions[direction]; // Sets the direction the snake is moving

                        Position snakeNewHead = new Position(snakeHead.row + nextDirection.row,
                                                             snakeHead.col + nextDirection.col); // Sets the new position of snake head based on the snake's direction

                        // Makes the snake come out from the other side of the window when it passes through the edge of the window
                        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;
                        }

                        //Replace mainloop = GameOver(obstacles, snakeElements, snakeNewHead, userPoints, userName) with below code;
                        if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                        {
                            //int lives = 3;
                            lives = lives - 1;
                            if (lives <= 0)
                            {
                                lives    = lives + 3;
                                mainloop = RealGameOver(obstacles, snakeElements, snakeNewHead, userPoints, userName);
                                state    = GameState.InMainMenu;
                            }
                            else
                            {
                                Lives(lives);
                                mainloop = true;
                            }
                        }
                        else
                        {
                            mainloop = true;
                        }

                        // Draws the snake's first body after the snake head in every frame
                        Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                        Console.ForegroundColor = ConsoleColor.DarkGray;
                        Console.Write("*");

                        // Adds the snake head into the snake element
                        snakeElements.Enqueue(snakeNewHead);

                        // Draws the snake head depending on which way the snake is facing
                        Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                        Console.ForegroundColor = ConsoleColor.Gray;
                        if (direction == right)
                        {
                            Console.Write(">");
                        }
                        if (direction == left)
                        {
                            Console.Write("<");
                        }
                        if (direction == up)
                        {
                            Console.Write("^");
                        }
                        if (direction == down)
                        {
                            Console.Write("v");
                        }

                        if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                        {
                            Console.Beep();
                            //If the snake's head intercepts the location of the food
                            // feeding the snake
                            food = MakeFood(randomNumbersGenerator, obstacles, snakeElements, determiner);

                            if (determiner == 0)
                            {
                                userPoints += 50;
                                seconds     = 15;
                            }

                            if (determiner == 1)
                            {
                                userPoints += 100;
                                seconds     = 15;
                            }

                            if (determiner == 2)
                            {
                                userPoints += 150;
                                seconds     = 15;
                            }
                            lastFoodTime = Environment.TickCount;
                            sleepTime--;

                            MakeNewObstacles(randomNumbersGenerator, obstacles, food, snakeElements);
                        }
                        else
                        {
                            // moving...
                            //Removes the last position of the snake by writing a space, pushing the snake forwards
                            Position last = snakeElements.Dequeue();
                            Console.SetCursorPosition(last.col, last.row);
                            Console.Write(" ");
                        }

                        if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                        {
                            //If the time limit has expired, Negative points are increased by 50
                            negativePoints = negativePoints + 50;
                            //Sets the cursor position to where the food was and deletes it by writing a space over it
                            Console.SetCursorPosition(food.col, food.row);
                            Console.Write(" ");
                            food = MakeFood(randomNumbersGenerator, obstacles, snakeElements, determiner);
                            //Resets the timer
                            lastFoodTime = Environment.TickCount;
                        }

                        //Sets the cursor position to the new column and row with the food
                        Console.SetCursorPosition(food.col - 1, food.row);

                        sleepTime -= 0.01;

                        Thread.Sleep((int)sleepTime);

                        if (level == Level.End)
                        {
                            mainloop = false;
                            state    = GameState.InMainMenu;
                        }
                    }
                }
                else if (state == GameState.InMainMenu)
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("\n <*** S N A K E ");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("\n - Start");
                    Console.WriteLine("\n - Scoreboard");
                    Console.WriteLine("\n - Help");
                    Console.WriteLine("\n - Quit");
                    Console.WriteLine(" ");
                    Console.WriteLine("Your selection: ");
                    string selection = Console.ReadLine().ToLower();
                    if (selection == "start")
                    {
                        state = GameState.Start;
                        Console.Clear();
                    }
                    else if (selection == "help")
                    {
                        Console.Clear();
                        state = GameState.Help;
                    }
                    else if (selection == "scoreboard")
                    {
                        Console.Clear();
                        state = GameState.ScorePage;
                    }
                    else if (selection == "quit")
                    {
                        break;
                    }
                    else
                    {
                        Console.WriteLine("Invalid Response");
                    }
                }
                else if (state == GameState.Help)
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("In this game, you play as a snake ( ***> ).");
                    Console.WriteLine(" ");
                    Console.WriteLine("Your goal is to eat the food ( @ ) before they disappear to grow in length");
                    Console.WriteLine(" ");
                    Console.WriteLine("Dodge obstacles ( = ) and do not hit yourself or you'll lose a life, once your lives runs out, you lose.");
                    Console.WriteLine(" ");
                    Console.WriteLine("The score is added each time a new food is eaten, and the final score is shown at game over");
                    Console.WriteLine(" ");
                    Console.WriteLine("Good luck!");
                    Console.WriteLine(" ");
                    Console.WriteLine("Type back to go back to main menu...");
                    string selection = Console.ReadLine().ToLower();
                    if (selection == "back")
                    {
                        Console.Clear();
                        state = GameState.InMainMenu;
                    }
                    else
                    {
                        Console.WriteLine("Invalid Response");
                    }
                }
                else if (state == GameState.ScorePage)
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Scoreboard");
                    Console.WriteLine();
                    string[] lines = File.ReadAllLines("../../scoreboard.txt", Encoding.UTF8);
                    foreach (string line in lines)
                    {
                        Console.WriteLine(line);
                    }
                    Console.WriteLine("Type back to go back to main menu...");
                    string selection = Console.ReadLine().ToLower();
                    if (selection == "back")
                    {
                        Console.Clear();
                        state = GameState.InMainMenu;
                    }
                    else
                    {
                        Console.WriteLine("Invalid Response");
                    }
                }
            }
        }
Exemplo n.º 9
0
        // Main
        static void Main(string[] args)
        {
            byte right                  = 0;
            byte left                   = 1;
            byte down                   = 2;
            byte up                     = 3;
            int  lastFoodTime           = 0;
            int  lastBonusTime          = 0;
            int  foodDissapearTime      = 15000;
            int  BonusFoodDisappearTime = 15000 / 3;
            int  negativePoints         = 0;

            Position[] directions = new Position[4];

            Program snake = new Program();

            //play main menu music
            MenuMusic();
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();



            List <string> menuListing = new List <string>()

            {
                "Start Game",
                "Previous Score",
                "Help",
                "Exit"
            };

            Console.CursorVisible = false;
            while (true)
            {
                Scoretxtfile();

                string selectedList = MainMenu(menuListing);
                if (selectedList == "Start Game")
                {
                    Console.Clear();

                    string PlayersName = InputName("Please Enter Your Name");

                    Console.Clear();

                    {
                        // play background music
                        snake.BackMusic();
                        // indicate direction with the index of array
                        snake.Dir(directions);
                        // reset the obstacle posion
                        List <Position> obstacles = new List <Position>();
                        snake.RandomObstacles(obstacles);

                        double sleepTime = 100;
                        int    direction = right;
                        Random randomNumbersGenerator = new Random();
                        Console.BufferHeight = Console.WindowHeight;
                        lastFoodTime         = Environment.TickCount;
                        lastBonusTime        = Environment.TickCount;

                        // Set Score to the top right
                        string scoretxt = "Score: 0";
                        snake.ScoreText(scoretxt, -5);
                        snake.PNames("Name: " + PlayersName);



                        Queue <Position> snakeElements = new Queue <Position>();
                        for (int i = 0; i <= 3; i++)
                        {
                            snakeElements.Enqueue(new Position(0, i));
                        }

                        Position food = new Position();
                        snake.GenFood(ref food, snakeElements, obstacles);

                        Position bonusfood = new Position();
                        snake.GenBonusFood(ref bonusfood, snakeElements, obstacles);

                        lastFoodTime  = Environment.TickCount;
                        lastBonusTime = Environment.TickCount;

                        foreach (Position position in snakeElements)
                        {
                            Console.SetCursorPosition(position.col, position.row);
                            snake.SnakeBody();
                        }

                        while (true)
                        {
                            TimeSpan timeSpan = TimeSpan.FromSeconds(Convert.ToInt32(stopwatch.Elapsed.TotalSeconds));
                            snake.TPlace("Time: " + timeSpan);
                            negativePoints++;

                            // old check user input
                            snake.UserInput(ref direction, right, left, down, up);

                            Position snakeHead     = snakeElements.Last();
                            Position nextDirection = directions[direction];

                            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;
                            }

                            if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                            {
                                //record the player's name and score in txt file
                                //Eddie
                                string playerText = PlayersName + "\t\t";
                                using (StreamWriter w = new StreamWriter("Player's Score.txt", true))
                                {
                                    w.WriteLine(playerText + score);
                                }

                                //----------Play Game Over Music------------
                                GameOverMusic();

                                //--------------------Game over text in red color----------------
                                Console.ForegroundColor = ConsoleColor.Red;

                                //------------first line--------------
                                string gameovertxt = "Gameover!";
                                snake.GameOverText(gameovertxt, 1);

                                int userPoints = (snakeElements.Count - 6) * 100 - negativePoints;
                                //if (userPoints < 0) userPoints = 0;
                                userPoints = Math.Max(userPoints, 0);

                                //------------second line--------------
                                string pointtxt = PlayersName + " your points are: " + score;
                                snake.GameOverText(pointtxt, 0);

                                string timertxt = PlayersName + " your total play time is :" + timeSpan;
                                snake.GameOverText(timertxt, -1);

                                //------------third line--------------
                                string exittxt = "Press Enter to Exit";
                                snake.GameOverText(exittxt, -2);

                                ////------------exit line--------------
                                string continuetxt = "Press any key to continue . . . .";
                                snake.EnterExit(continuetxt, -3);
                            }

                            Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                            snake.SnakeBody();

                            snakeElements.Enqueue(snakeNewHead);
                            Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                            Console.ForegroundColor = ConsoleColor.Gray;
                            if (direction == right)
                            {
                                Console.Write(">");
                            }
                            if (direction == left)
                            {
                                Console.Write("<");
                            }
                            if (direction == up)
                            {
                                Console.Write("^");
                            }
                            if (direction == down)
                            {
                                Console.Write("v");
                            }


                            if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                            {
                                // feeding the snake
                                do
                                {
                                    food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                                        randomNumbersGenerator.Next(0, Console.WindowWidth));
                                }while (snakeElements.Contains(food) || obstacles.Contains(food));
                                lastFoodTime = Environment.TickCount;
                                Console.SetCursorPosition(food.col, food.row);
                                DrawFood();
                                Position obstacle = new Position();

                                sleepTime--;
                                UpdateScore();


                                if (score >= winScore)
                                {
                                    //record the player's name and score in txt file
                                    //Eddie
                                    string playerText = PlayersName + "\t\t";
                                    using (StreamWriter w = new StreamWriter("Player's Score.txt", true))
                                    {
                                        w.WriteLine(playerText + score);
                                    }

                                    // won text in green color
                                    Console.ForegroundColor = ConsoleColor.Green;

                                    //play winning music
                                    WinMusic();

                                    //------------first line--------------
                                    string wintxt = "You Won!";
                                    snake.GameOverText(wintxt, 1);

                                    int userPoints = (snakeElements.Count - 6) * 100 - negativePoints;
                                    //if (userPoints < 0) userPoints = 0;
                                    userPoints = Math.Max(userPoints, 0);

                                    //------------second line--------------
                                    string pointtxt = "Your points are: " + score;
                                    snake.GameOverText(pointtxt, 0);

                                    //------------third line--------------
                                    string exittxt = "Press Enter to Exit";
                                    snake.GameOverText(exittxt, -1);

                                    ////------------exit line--------------
                                    string continuetxt = "Press any key to continue . . .";
                                    snake.EnterExit(continuetxt, 0);
                                }

                                do
                                {
                                    obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                                }while (snakeElements.Contains(obstacle) ||
                                        obstacles.Contains(obstacle) ||
                                        (food.row != obstacle.row && food.col != obstacle.row));
                                obstacles.Add(obstacle);
                                Console.SetCursorPosition(obstacle.col, obstacle.row);
                                DrawObs();
                            }

                            if (snakeNewHead.col == bonusfood.col && snakeNewHead.row == bonusfood.row)
                            {
                                score += 150;
                                UpdateScore();
                                DrawFood();
                                while (snakeElements.Contains(food) || obstacles.Contains(food))
                                {
                                    ;
                                }
                                lastFoodTime = Environment.TickCount;
                                Console.SetCursorPosition(food.col, food.row);
                                Position obstacle = new Position();
                                // If reach score == winScore(10500), WIN
                                if (score >= winScore)
                                {
                                    //record the player's name and score in txt file
                                    //Eddie
                                    string playerText = PlayersName + "\t\t";
                                    using (StreamWriter w = new StreamWriter("Player's Score.txt", true))
                                    {
                                        w.WriteLine(playerText + score);
                                    }

                                    // won text in green color
                                    Console.ForegroundColor = ConsoleColor.Green;

                                    //play winning music
                                    WinMusic();

                                    //------------first line--------------
                                    string wintxt = "You Won!";
                                    snake.GameOverText(wintxt, 1);

                                    int userPoints = (snakeElements.Count - 6) * 100 - negativePoints;
                                    //if (userPoints < 0) userPoints = 0;
                                    userPoints = Math.Max(userPoints, 0);

                                    //------------second line--------------
                                    string pointtxt = "Your points are: " + score;
                                    snake.GameOverText(pointtxt, 0);

                                    //------------third line--------------
                                    string exittxt = "Press Enter to Exit";
                                    snake.GameOverText(exittxt, -1);

                                    ////------------exit line--------------
                                    string continuetxt = "Press any key to continue . . .";
                                    snake.EnterExit(continuetxt, 0);
                                    while (Console.ReadKey(true).Key != ConsoleKey.Enter)
                                    {
                                    }
                                    Console.Clear();
                                }
                            }
                            else
                            {
                                // moving...
                                Position last = snakeElements.Dequeue();
                                Console.SetCursorPosition(last.col, last.row);
                                Console.Write(" ");
                            }

                            if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                            {
                                negativePoints = negativePoints + 50;
                                Console.SetCursorPosition(food.col, food.row);
                                Console.Write(" ");
                                snake.GenFood(ref food, snakeElements, obstacles);
                                lastFoodTime = Environment.TickCount;
                            }

                            // bomus food disapear
                            else if (Environment.TickCount - lastBonusTime >= BonusFoodDisappearTime)
                            {
                                negativePoints = negativePoints + 50;
                                Console.SetCursorPosition(bonusfood.col, bonusfood.row);
                                Console.Write(" ");
                                snake.GenBonusFood(ref bonusfood, snakeElements, obstacles);
                                lastBonusTime = Environment.TickCount;
                            }

                            Console.SetCursorPosition(food.col, food.row);
                            DrawFood();

                            sleepTime -= 0.01;

                            Thread.Sleep((int)sleepTime);
                        }
                    }
                }


                else if (selectedList == "Previous Score")
                {
                    Console.Clear();

                    //read the text file
                    string[] lines = System.IO.File.ReadAllLines("Player's Score.txt");

                    //Display the file using foreach loop.
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    System.Console.WriteLine("\n \t Previous Player \n");
                    foreach (string line in lines)
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine("\t" + line);
                    }

                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("\n \t Press Enter to Exit");
                    while (Console.ReadKey(true).Key != ConsoleKey.Enter)
                    {
                    }
                    Console.Clear();
                }

                else if (selectedList == "Help")
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    snake.Helptxt("Help", 5);
                    Console.ForegroundColor = ConsoleColor.White;
                    snake.Helptxt("You must enter your name before the game start", 3);
                    snake.Helptxt("To move Upward press Up Arrow Key [^]", 2);
                    snake.Helptxt("To move Downward press Down Arrow Key [v]", 1);
                    snake.Helptxt("To move Left press Left Arrow Key [<]", 0);
                    snake.Helptxt("To move Right press Right Arrow Key [>]", -1);
                    Console.ForegroundColor = ConsoleColor.Red;
                    snake.Helptxt("Press Enter to Exit", -3);
                    while (Console.ReadKey(true).Key != ConsoleKey.Enter)
                    {
                    }
                    Console.Clear();
                }
                else if (selectedList == "Exit")
                {
                    System.Environment.Exit(0);
                }
            }
        }
Exemplo n.º 10
0
        //the main compiler

        static void Main(string[] args)
        {
            MainMenu startgame    = new MainMenu();
            byte     right        = 0;
            byte     left         = 1;
            byte     down         = 2;
            byte     up           = 3;
            int      lastFoodTime = 0;
            //The food relocate's timer (adjusted)
            int    foodDissapearTime = 15000;
            int    negativePoints    = 0;
            int    userPoints        = 0;
            double sleepTime         = 100;

            Game game1 = new Game();

            //Background Music (Looping)
            //Continue the background music after snake eat the food
            MediaPlayer backgroundMusic = new MediaPlayer();

            backgroundMusic.Open(new System.Uri(Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wii.wav")));



            bool gameLoop = false;


            startgame.mainMenu();
            string userOption = Console.ReadLine();

            if (userOption == "1")
            {
                Console.Clear();
                gameLoop = true;
            }
            else if (userOption == "2")
            {
                Console.WriteLine("ScoreBoard");
            }
            else if (userOption == "3")
            {
                gameLoop = false;
                Environment.Exit(0);
            }



            Position[] directions = new Position[]
            {
                new Position(0, 1),  // right
                new Position(0, -1), // left
                new Position(1, 0),  // down
                new Position(-1, 0), // up
            };

            //this defaults the snake's direction to right when the game starts
            int    direction = right;
            Random randomNumbersGenerator = new Random();

            Console.BufferHeight = Console.WindowHeight;
            lastFoodTime         = Environment.TickCount;

            //Make a list of coordinates of the position
            List <Position> obstacles = new List <Position>();

            //5 obstacles have been created while the game start running with different position
            for (int i = 0; i < 5; i++)
            {
                obstacles.Add(new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)));
            }


            // For loop for creating the obstacles
            foreach (Position obstacle in obstacles)
            {
                game1.createObstacle(obstacle);
            }


            Queue <Position> snakeElements = new Queue <Position>();

            //change 5 to 3 to make the default size of the snake to 3 upon start
            for (int i = 0; i <= 3; i++)
            {
                snakeElements.Enqueue(new Position(0, i));
            }


            //creating food item
            Position food;

            do
            {
                food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                    randomNumbersGenerator.Next(0, Console.WindowWidth));
            }while (snakeElements.Contains(food) || obstacles.Contains(food));

            game1.createFood(food);

            //the body of the snake
            foreach (Position position in snakeElements)
            {
                game1.createSnakeBody(position);
            }

            while (gameLoop)
            {
                negativePoints++;
                //background music (looping)
                backgroundMusic.Play();
                if (backgroundMusic.Position >= new TimeSpan(0, 0, 29))
                {
                    backgroundMusic.Position = new TimeSpan(0, 0, 0);
                }

                //control keys
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userInput = Console.ReadKey();
                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        if (direction != right)
                        {
                            direction = left;
                        }
                    }
                    if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        if (direction != left)
                        {
                            direction = right;
                        }
                    }
                    if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        if (direction != down)
                        {
                            direction = up;
                        }
                    }
                    if (userInput.Key == ConsoleKey.DownArrow)
                    {
                        if (direction != up)
                        {
                            direction = down;
                        }
                    }
                }
                //apart from giving the snake directions on where to move, it also ensures that the snake doesnt move the opposite direction directly

                Position snakeHead     = snakeElements.Last();
                Position nextDirection = directions[direction];

                Position snakeNewHead = new Position(snakeHead.row + nextDirection.row,
                                                     snakeHead.col + nextDirection.col);

                //This is to display the player score
                Console.SetCursorPosition(0, 0);
                Console.ForegroundColor = ConsoleColor.White;
                //if (userPoints < 0) userPoints = 0;
                userPoints = Math.Max(userPoints, 0);
                Console.WriteLine("Your points are: {0} \t REACH 10 POINTS TO WIN", userPoints);

                //this is the game over scene after the player loses the game either by the snake colliding with itself or the snake colliding with obstacles
                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead) || (snakeNewHead.col < 0) || (snakeNewHead.row < 0) || (snakeNewHead.row >= Console.WindowHeight) || (snakeNewHead.col >= Console.WindowWidth))
                {
                    //When the snake hit the obstacle sound effect (Game Over)
                    SoundPlayer sound1 = new SoundPlayer("die.wav");
                    sound1.Play();

                    game1.gameOverScreen(userPoints);

                    using (StreamWriter file = new StreamWriter("Score.txt", true))
                    {
                        file.WriteLine("Score: " + userPoints + "\tSnake Length: " + snakeElements.Count + "\tLOSS");
                    }
                    return;
                }
                else if (userPoints == 10) //winning condition
                {
                    //This sound plays when the player wins
                    SoundPlayer sound2 = new SoundPlayer("gamestart.wav");
                    sound2.Play();

                    game1.gameWon();

                    using (StreamWriter file = new StreamWriter("Score.txt", true))
                    {
                        file.WriteLine("Score: " + userPoints + "\tSnake Length:" + snakeElements.Count + "\tWIN");
                    }
                    return;
                }

                game1.createSnakeBody(snakeHead);

                //whenever the snake changes direction, the head of the snake changes according to the direction
                snakeElements.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                Console.ForegroundColor = ConsoleColor.Gray;
                if (direction == right)
                {
                    Console.Write(">");
                }
                if (direction == left)
                {
                    Console.Write("<");
                }
                if (direction == up)
                {
                    Console.Write("^");
                }
                if (direction == down)
                {
                    Console.Write("v");
                }

                // feeding the snake
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row) //if snake head's coordinates is same with food
                {
                    //Increase snake movement speed when eating the food
                    sleepTime -= 10.00;

                    //Snake eat food sound effect
                    SoundPlayer sound3 = new SoundPlayer("food.wav");
                    sound3.Play();

                    //add one point when food is eaten
                    userPoints++;

                    //creates new food
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));

                    lastFoodTime = Environment.TickCount;
                    game1.createFood(food);
                    sleepTime--;

                    //creates new obstacle
                    Position obstacle = new Position();
                    do
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                                randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(obstacle) || obstacles.Contains(obstacle) || (food.row != obstacle.row && food.col != obstacle.row));
                    obstacles.Add(obstacle);
                    game1.createObstacle(obstacle);
                }
                else
                {
                    // moving...
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(" ");
                }

                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints = negativePoints + 50;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write(" ");
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    lastFoodTime = Environment.TickCount;
                }

                game1.createFood(food);

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 11
0
        public void Program()
        {
            byte   right             = 0;
            byte   left              = 1;
            byte   down              = 2;
            byte   up                = 3;
            int    lastFoodTime      = 0;
            int    negativePoints    = 0;
            int    foodDissapearTime = 0;
            double sleepTime         = 0;
            int    score             = 0;

            Position[] directions = new Position[4];
            Random     rand       = new Random();
            int        showMenu   = 0;



            while (showMenu == 0)
            {
                showMenu = MainMenu();//main menu
            }
            if (showMenu == 1)
            { // Normal Mode
                foodDissapearTime = 15000;
                sleepTime         = 100;
            }
            if (showMenu == 2)
            {     // Hard Mode
                foodDissapearTime = 7500;
                sleepTime         = 50;
            }

            if (showMenu == 3)
            {       //Extreme Mode
                foodDissapearTime = 3750;
                sleepTime         = 25;
            }
            Snake s = new Snake();

            // Define direction with characteristic of index of array
            s.BgMusic();
            s.Direction(directions);
            List <Position> obstacles = new List <Position>();

            if (showMenu == 1)
            {
                s.Obstacles(obstacles);
            }
            if (showMenu == 2)
            {
                s.Obstacles(obstacles);
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
            }

            if (showMenu == 3)
            {
                s.Obstacles(obstacles);
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
                obstacles.Add(new Position(rand.Next(1, Console.WindowHeight), rand.Next(0, Console.WindowWidth)));
            }
            //Initializes the direction of the snakes head and the food timer and the speed of the snake.
            int direction = right;

            Console.BufferHeight = Console.WindowHeight;
            lastFoodTime         = Environment.TickCount;
            Console.Clear();
            Thread.Sleep(2000);
            //Loop to show obstacles in the console window
            foreach (Position obstacle in obstacles)
            {
                Console.SetCursorPosition(obstacle.col, obstacle.row);
                s.DrawObstacle();
            }
            //Initialise the snake position in top left corner of the windows
            //The snakes length is reduced to 3* instead of 5.
            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(2, i));
            }
            //To position food randomly in the console
            Position food = new Position();

            do
            {
                food = new Position(rand.Next(0, Console.WindowHeight), //Food generated within limits of the console height
                                    rand.Next(0, Console.WindowWidth)); //Food generated within the limits of the console width
            }
            //loop to continue putting food in the game
            //put food in random places with "@" symbol
            while (snakeElements.Contains(food) || obstacles.Contains(food));
            Console.SetCursorPosition(food.col, food.row);
            s.DrawFood();
            //during the game, the snake is shown with "*" symbol
            foreach (Position position in snakeElements)
            {
                Console.SetCursorPosition(position.col, position.row);
                s.DrawSnakeBody();
            }
            while (true)
            {
                //negative points increased if the food is not eaten in time
                negativePoints++;
                s.CheckUserInput(ref direction, right, left, down, up);
                //Manages the position of the snakes head.
                Position snakeHead     = snakeElements.Last();
                Position nextDirection = directions[direction];
                //Snake position when it goes through the terminal sides
                Position snakeNewHead = new Position(snakeHead.row + nextDirection.row,
                                                     snakeHead.col + nextDirection.col);
                if (snakeNewHead.col < 0)
                {
                    snakeNewHead.col = Console.WindowWidth - 1;
                }
                //Snake cannot move into the score column with changes in this part of the code
                if (snakeNewHead.row < 1)
                {
                    snakeNewHead.row = Console.WindowHeight - 1;
                }
                if (snakeNewHead.row >= Console.WindowHeight)
                {
                    snakeNewHead.row = 1;
                }
                if (snakeNewHead.col >= Console.WindowWidth)
                {
                    snakeNewHead.col = 0;
                }

                int gameOver = s.GameOver(snakeElements, snakeNewHead, negativePoints, obstacles);
                if (gameOver == 1)     //if snake hits an obstacle then its gameover
                {
                    return;
                }
                //The position of the snake head according the body
                Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                s.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.DarkRed;
                if (direction == right)
                {
                    Console.Write(">");                         //Snakes head when moving right
                }
                if (direction == left)
                {
                    Console.Write("<");                       //Snakes head when moving left
                }
                if (direction == up)
                {
                    Console.Write("^");                     //Snakes head when moving up
                }
                if (direction == down)
                {
                    Console.Write("v");                       //Snakes head when moving down
                }
                // food will be positioned in different column and row from snakes head and will not touch the score shown on console
                if ((snakeNewHead.col == food.col + 1 && snakeNewHead.row == food.row) || (snakeNewHead.col == food.col + 1 && snakeNewHead.row == food.row))
                {
                    if (snakeNewHead.col == food.col + 1 && snakeNewHead.row == food.row)
                    {
                        score += (snakeElements.Count);
                    }
                    Scoreboard.Show("Current Score", 0, 1);
                    Scoreboard.WriteScore(score, 0, 2);
                    Console.Beep();    //Beep when food is eaten
                    do
                    {
                        food = new Position(rand.Next(0, Console.WindowHeight),
                                            rand.Next(0, Console.WindowWidth));
                    }
                    //if the snake consumes the food, lastfoodtime will be reset
                    //new food will be drawn and the snakes speed will increase
                    while (snakeElements.Contains(food) || obstacles.Contains(food));
                    lastFoodTime = Environment.TickCount;
                    Console.SetCursorPosition(food.col, food.row);
                    s.DrawFood();
                    sleepTime--;
                    //setting the obstacles in the game randomly
                    Position obstacle = new Position();
                    do
                    {
                        obstacle = new Position(rand.Next(0, Console.WindowHeight),
                                                rand.Next(0, Console.WindowWidth));
                    }
                    //new obstacle will not be placed in the current position of the snake and previous obstacles.
                    //new obstacle will not be placed at the same row & column of food
                    while (snakeElements.Contains(obstacle) ||
                           obstacles.Contains(obstacle) ||
                           (food.row != obstacle.row && food.col != obstacle.row));
                    obstacles.Add(obstacle);
                    //new obstacles will not be placed on the score
                    Console.SetCursorPosition(obstacle.col + 1, obstacle.row);
                    s.DrawObstacle();
                }
                else
                {
                    // snakes movement shown by blank spaces
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(" ");
                }
                //if snake didnt eat in time, 50 will be added to negative points
                //draw new food randomly after the previous one is eaten
                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints = negativePoints + 50;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write(" ");
                    do
                    {
                        food = new Position(rand.Next(0, Console.WindowHeight),
                                            rand.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    lastFoodTime = Environment.TickCount;
                }
                //draw food with @ symbol
                Console.SetCursorPosition(food.col, food.row);
                s.DrawFood();
                //snake moving speed increased by 0.01.
                sleepTime -= 0.01;
                //pause the execution of snake moving speed
                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            Position[] directions = new Position[]
            {
                new Position(0, 1),                 // right
                new Position(0, -1),                // left
                new Position(1, 0),                 // down
                new Position(-1, 0),                // up
            };

            byte right = 0;
            byte left  = 1;
            byte down  = 2;
            byte up    = 3;

            Console.WriteLine("Choose difficulty: ");
            Console.WriteLine("Easy");
            Console.WriteLine("Medium");
            Console.WriteLine("Hard");

            string difficulty = Console.ReadLine();

            Console.Clear();

            double sleepTime = 100;

            int direction = right;

            Console.BufferHeight = Console.WindowHeight;

            Random   randomNumbersGenerator = new Random();
            Position food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next
                                             (0, Console.WindowWidth));

            Console.SetCursorPosition(food.col, food.row);
            Console.Write("@");

            Queue <Position> snakeElements = new Queue <Position>();

            for (int i = 0; i < 6; ++i)
            {
                snakeElements.Enqueue(new Position(0, i));
            }

            foreach (Position position in snakeElements)
            {
                Console.SetCursorPosition(position.col, position.row);
                Console.Write('*');
            }


            while (true)
            {
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userInput = Console.ReadKey();

                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        if (direction != right)
                        {
                            direction = left;
                        }
                    }
                    else if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        if (direction != left)
                        {
                            direction = right;
                        }
                    }
                    else if (userInput.Key == ConsoleKey.DownArrow)
                    {
                        if (direction != up)
                        {
                            direction = down;
                        }
                    }
                    else if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        if (direction != down)
                        {
                            direction = up;
                        }
                    }
                }

                Position snakeHead     = snakeElements.Last();
                Position nextDirection = directions[direction];

                Position snakeNewHead = new Position(snakeHead.row + nextDirection.row, snakeHead.col + nextDirection.col);


                if (snakeNewHead.row < 0 ||
                    snakeNewHead.col < 0 ||
                    snakeNewHead.row >= Console.WindowHeight ||
                    snakeNewHead.col >= Console.WindowWidth ||
                    snakeElements.Contains(snakeNewHead))
                {
                    Console.SetCursorPosition(0, 0);
                    Console.WriteLine("Game Over!");
                    Console.WriteLine("Highscore: {0}", (snakeElements.Count - 6) * 100);
                    return;
                }

                snakeElements.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                Console.Write('*');

                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                {
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next
                                                (0, Console.WindowWidth));
                    }while (snakeElements.Contains(food));

                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write("@");

                    sleepTime--;
                    //snake eats
                }
                else
                {
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(' ');
                }



                //Console.Clear();

                if (difficulty == "Easy")
                {
                    sleepTime -= 0.01;
                }
                else if (difficulty == "Medium")
                {
                    sleepTime -= 0.03;
                }
                else if (difficulty == "Hard")
                {
                    sleepTime -= 0.07;
                }
                else
                {
                    Console.WriteLine("Congrats, idiot!");
                    sleepTime -= 20;
                }


                sleepTime -= 0.01;
                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            System.Media.SoundPlayer move     = new System.Media.SoundPlayer(@"C:\Users\User\Desktop\Snake\Snake\sound\move.wav");
            System.Media.SoundPlayer eat      = new System.Media.SoundPlayer(@"C:\Users\User\Desktop\Snake\Snake\sound\eat.wav");
            System.Media.SoundPlayer gameover = new System.Media.SoundPlayer(@"C:\Users\User\Desktop\Snake\Snake\sound\gameover.wav");
            System.Media.SoundPlayer crash    = new System.Media.SoundPlayer(@"C:\Users\User\Desktop\Snake\Snake\sound\crash.wav");
            byte   right             = 0;
            byte   left              = 1;
            byte   down              = 2;
            byte   up                = 3;
            int    lastFoodTime      = 0;
            int    foodDissapearTime = 12000;
            int    negativePoints    = 0;
            double sleepTime         = 100;
            int    direction         = right; // To make the snake go to the right when the program starts

            Random randomNumbersGenerator = new Random();

            Console.BufferHeight = Console.WindowHeight;
            lastFoodTime         = Environment.TickCount;

            // Make sure the snake spawn with just 3 "*"s and spawn it on the top left of the screen

            Queue <Position> snakeElements = new Queue <Position>();

            for (int i = 0; i <= 3; i++) //spawn snake body
            {
                snakeElements.Enqueue(new Position(0, i));
            }

            // Spawn the first 5 obstacles in the game

            List <Position> obstacles = new List <Position>() //spawn the first obstacles
            {
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
            };

            foreach (Position obstacle in obstacles) //write obstacle as "=" on declared position
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.SetCursorPosition(obstacle.y, obstacle.x);
                Console.Write("=");
            }

            //Food Creation

            Position food;

            do //randomize where the food spawns
            {
                food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                    randomNumbersGenerator.Next(0, Console.WindowWidth));
            }while (snakeElements.Contains(food) || obstacles.Contains(food)); //to make sure that food doesnt spawn on both snake and obstacles


            //Movement implementation

            Position[] directions = new Position[]
            {
                new Position(0, 1),  // right
                new Position(0, -1), // left
                new Position(1, 0),  // down
                new Position(-1, 0), // up
            };

            while (true) //read the direction of arrow key which user inputted
            {
                negativePoints++;

                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userInput = Console.ReadKey();
                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        if (direction != right)
                        {
                            direction = left;
                        }
                        move.Play();
                    }
                    if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        if (direction != left)
                        {
                            direction = right;
                        }
                        move.Play();
                    }
                    if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        if (direction != down)
                        {
                            direction = up;
                        }
                        move.Play();
                    }
                    if (userInput.Key == ConsoleKey.DownArrow)
                    {
                        if (direction != up)
                        {
                            direction = down;
                        }
                        move.Play();
                    }
                }


                //Creating the snake:

                Position snakeHead     = snakeElements.Last();  //make sure the head of the snake is spawned at the end of the "*" position
                Position nextDirection = directions[direction]; //initialize which direction is inputted

                Position snakeNewHead = new Position(snakeHead.x + nextDirection.x,
                                                     snakeHead.y + nextDirection.y); //snakehead will move to the same direction to which the user inputted

                // make sure the snake wont be able to go outside the screen
                if (snakeNewHead.y < 0)
                {
                    snakeNewHead.y = Console.WindowWidth - 1;
                }
                if (snakeNewHead.x < 0)
                {
                    snakeNewHead.x = Console.WindowHeight - 1;
                }
                if (snakeNewHead.x >= Console.WindowHeight)
                {
                    snakeNewHead.x = 0;
                }
                if (snakeNewHead.y >= Console.WindowWidth)
                {
                    snakeNewHead.y = 0;
                }

                foreach (Position position in snakeElements) //writes the body of the snake as "*" on declared position
                {
                    Console.SetCursorPosition(position.y, position.x);
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    Console.Write("*");
                }

                int userPoints = (snakeElements.Count - 4) * 100;

                // Show and update the score of the player

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.SetCursorPosition(110, 0);
                Console.Write("Score: {0}", userPoints);

                // the game will be over when the snake hits it body or the obstacles

                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                {
                    gameover.Play();

                    Console.SetCursorPosition(50, 6);

                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Game over!");
                    //if (userPoints < 0) userPoints = 0;

                    Console.SetCursorPosition(45, 7);
                    Console.WriteLine("Your points are: {0}", userPoints);

                    Console.SetCursorPosition(35, 8);
                    Console.WriteLine("Please press the ENTER key to exit the game.");

                    string nametext = Console.ReadLine();

                    using (System.IO.StreamWriter file =
                               new System.IO.StreamWriter(@"C:\Users\joe_y\Desktop\Snaketest\score.txt", true))
                    {
                        file.WriteLine(nametext + " - " + userPoints.ToString());
                    }
                    Console.WriteLine("Please press the ENTER key to exit the game."); //true here mean we won't output the key to the console, just cleaner in my opinion.

                    ConsoleKeyInfo keyInfo = Console.ReadKey(true);
                    if (keyInfo.Key == ConsoleKey.Enter)
                    {
                        return;
                    }
                }


                // The game will be over and user will win if they reached 1000 points

                if (userPoints == 1000)
                {
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Congrats! You've won the game!");
                    Console.WriteLine("Your points are: {0}", userPoints);
                    int loopcount = 0;
                    while (Console.ReadKey().Key != ConsoleKey.Enter)
                    {
                        if (Console.ReadKey().Key == ConsoleKey.Enter)
                        {
                            return;
                        }
                        loopcount = +1;
                    }
                }

                // writes the head of the snake as ">","<","^","v" to the position it is declared
                snakeElements.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.y, snakeNewHead.x);
                Console.ForegroundColor = ConsoleColor.Gray;
                if (direction == right)
                {
                    Console.Write(">");
                }
                if (direction == left)
                {
                    Console.Write("<");
                }
                if (direction == up)
                {
                    Console.Write("^");
                }
                if (direction == down)
                {
                    Console.Write("v");
                }


                //What will happened if the snake got fed:
                if (snakeNewHead.y == food.y && snakeNewHead.x == food.x)
                {
                    // Things that will be happening with the FOOD once it got ate by the snake
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), //randomize the new position of the food
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));            //writes "@" to indicate food to the designated position it randomized
                    eat.Play();
                    lastFoodTime = Environment.TickCount;
                    sleepTime--;

                    // Things that will be happening with the OBSTACLE once the FOOD got ate by the snake

                    Position obstacle = new Position(); // randomize the position of the obstacles
                    do
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                                randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(obstacle) ||
                            obstacles.Contains(obstacle) ||
                            (food.x != obstacle.x && food.y != obstacle.y));
                    obstacles.Add(obstacle);
                    Console.SetCursorPosition(obstacle.y, obstacle.x);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("=");
                }
                else
                {
                    // moving...
                    Position last = snakeElements.Dequeue(); // basically moving the snake and delete the last "body part" of the snake to maintain the length of the snake
                    Console.SetCursorPosition(last.y, last.x);
                    Console.Write(" ");
                }


                // Initialize the time taken for the food to spawn if the snake doesn't eat it

                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints = negativePoints + 50;
                    Console.SetCursorPosition(food.y, food.x);
                    Console.Write(" ");
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    lastFoodTime = Environment.TickCount;
                }

                Console.SetCursorPosition(food.y, food.x);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("@");

                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 14
0
        //Defines the Main method
        static void Main(string[] args)
        {
            ///<summary>
            /// Create variables.
            /// </summary>
            byte right             = 0;
            byte left              = 1;
            byte down              = 2;
            byte up                = 3;
            int  lastFoodTime      = 0;
            int  foodDissapearTime = 10000;
            int  negativePoints    = 0;
            int  eatenTimes        = 0;
            int  lvlNum            = 1;
            int  bonus             = 0;

            /* Create an array of structures named directions and pre-define the positions that follow the format of the structure named Position*/
            Position[] directions = new Position[]
            {
                new Position(0, 1),  // right
                new Position(0, -1), // left
                new Position(1, 0),  // down
                new Position(-1, 0), // up
            };
            double sleepTime = 100;  //Stores numbers with decimal
            int    direction = right;
            Random randomNumbersGenerator = new Random();

            Console.BufferHeight = Console.WindowHeight;
            lastFoodTime         = Environment.TickCount;     //Timer

            ///<summary>
            /// Create a list named obstacles to store the position of the obstacles.
            /// </summary>
            List <Position> obstacles = new List <Position>()
            {
                new Position(12, 12),
                new Position(14, 20),
                new Position(7, 7),
                new Position(19, 19),
                new Position(6, 9),
            };

            Program program = new Program();

            program.helpMenu();
            program.playBackgroundSound();

            program.placeObstacles(obstacles);

            //Create a Queue to store elements in FIFO (first-in, first out) style
            Queue <Position> snakeElements = new Queue <Position>();

            program.addSnakeElements(snakeElements);
            program.displayLevel(lvlNum);
            program.displayScore(snakeElements, negativePoints, bonus);

            ///<summary>
            /// Set up and draw the food of the snake at random position.
            /// </summary>
            Position food;

            do
            {
                food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                    randomNumbersGenerator.Next(4, Console.WindowWidth));
            }while (snakeElements.Contains(food) || obstacles.Contains(food));

            Position bonusfood;

            do
            {
                bonusfood = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                         randomNumbersGenerator.Next(4, Console.WindowWidth));
            }while (snakeElements.Contains(bonusfood) || obstacles.Contains(bonusfood));

            program.drawFood(food);
            program.drawSpecialFood(bonusfood, randomNumbersGenerator, eatenTimes);
            program.drawSnakeBody(snakeElements);

            ///<summary>
            /// A while loop which allow the user to control the snake by using the keyboard to create input.
            /// </summary>
            while (true)
            {
                //negativePoints++;
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userInput = new ConsoleKeyInfo();
                    do
                    {
                        if (Console.KeyAvailable == false)
                        {
                        }

                        userInput = Console.ReadKey(true);
                        if (userInput.Key == ConsoleKey.LeftArrow)
                        {
                            if (direction != right)
                            {
                                direction = left;
                            }
                        }
                        if (userInput.Key == ConsoleKey.RightArrow)
                        {
                            if (direction != left)
                            {
                                direction = right;
                            }
                        }
                        if (userInput.Key == ConsoleKey.UpArrow)
                        {
                            if (direction != down)
                            {
                                direction = up;
                            }
                        }
                        if (userInput.Key == ConsoleKey.DownArrow)
                        {
                            if (direction != up)
                            {
                                direction = down;
                            }
                        }
                    } while (userInput.Key != ConsoleKey.LeftArrow && userInput.Key != ConsoleKey.RightArrow &&
                             userInput.Key != ConsoleKey.UpArrow && userInput.Key != ConsoleKey.DownArrow);
                }

                //snakeHead is the last element of snakeElements
                Position snakeHead = snakeElements.Last();

                ///<summary>
                /// Identify the direction of the snake.
                /// </summary>
                Position nextDirection = directions[direction];

                ///<summary>
                /// Manage the length of the snake.
                /// </summary>
                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;
                }

                program.createBoundary();
                if ((snakeHead.row == 4) || (snakeNewHead.row == 4))
                {
                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo userInput = Console.ReadKey();

                        do
                        {
                            if (Console.KeyAvailable == false)
                            {
                            }

                            userInput = Console.ReadKey(true);
                            if (userInput.Key == ConsoleKey.LeftArrow)
                            {
                                if (direction != right)
                                {
                                    direction = left;
                                }
                            }
                            if (userInput.Key == ConsoleKey.RightArrow)
                            {
                                if (direction != left)
                                {
                                    direction = right;
                                }
                            }
                            if (userInput.Key == ConsoleKey.UpArrow)
                            {
                                if (direction != down)
                                {
                                    direction = up;
                                }
                            }
                            if (userInput.Key == ConsoleKey.DownArrow)
                            {
                                if (direction != up)
                                {
                                    direction = down;
                                }
                            }
                        } while (userInput.Key != ConsoleKey.LeftArrow && userInput.Key != ConsoleKey.RightArrow && userInput.Key != ConsoleKey.UpArrow && userInput.Key != ConsoleKey.DownArrow);
                    }
                    else
                    {
                    }
                }
                else
                {
                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo userInput = Console.ReadKey();

                        do
                        {
                            if (Console.KeyAvailable == false)
                            {
                            }

                            userInput = Console.ReadKey(true);
                            if (userInput.Key == ConsoleKey.LeftArrow)
                            {
                                if (direction != right)
                                {
                                    direction = left;
                                }
                            }
                            if (userInput.Key == ConsoleKey.RightArrow)
                            {
                                if (direction != left)
                                {
                                    direction = right;
                                }
                            }
                            if (userInput.Key == ConsoleKey.DownArrow)
                            {
                                if (direction != up)
                                {
                                    direction = down;
                                }
                            }
                        } while (userInput.Key != ConsoleKey.LeftArrow && userInput.Key != ConsoleKey.RightArrow && userInput.Key != ConsoleKey.DownArrow);
                    }
                }

                ///<summary>
                /// End the game and print the score(s) of the user when the snake hit the obstacles.
                /// </summary>
                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead) || (snakeHead.row < 2) || (snakeNewHead.row < 2) || (snakeHead.row == Console.WindowHeight) || (snakeNewHead.row == Console.WindowHeight))
                {
                    program.gameOver(snakeElements, negativePoints, bonus, lvlNum);

                    string action = Console.ReadLine();                     //Enter key pressed, exit game
                    if (action == "")
                    {
                        return;
                    }
                }

                ///<summary>
                /// Draw the body of the snake.
                /// </summary>
                Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");

                ///<summary>
                /// Direction of the head of the snake when the user changes the direction of the snake.
                /// </summary>
                snakeElements.Enqueue(snakeNewHead);
                program.displayLevel(lvlNum);
                program.displayScore(snakeElements, negativePoints, bonus);

                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                Console.ForegroundColor = ConsoleColor.Gray;

                program.writeDirection(direction, right, left, up, down);

                ///<summary>
                /// Creation of the new food after the snake ate the previous food.
                /// </summary>
                if ((snakeNewHead.col == food.col && snakeNewHead.row == food.row) || (snakeNewHead.col == food.col + 1 && snakeNewHead.row == food.row))
                {
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write("  ");

                    eatenTimes++;

                    if (eatenTimes == 2)
                    {
                        lvlNum++;
                        program.displayLevel(lvlNum);
                        foodDissapearTime = 8000;
                    }

                    if (eatenTimes == 3)
                    {
                        lvlNum++;
                        program.displayLevel(lvlNum);
                        foodDissapearTime = 7000;
                    }

                    if (eatenTimes == 4)
                    {
                        lvlNum++;
                        program.displayLevel(lvlNum);
                        foodDissapearTime = 6000;
                    }

                    if (eatenTimes == 5)
                    {
                        lvlNum++;
                        program.displayLevel(lvlNum);
                    }

                    // feeding the snake
                    //find new position for food
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(4, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    program.winGame(negativePoints, eatenTimes, snakeElements, bonus, lvlNum);

                    program.drawFood(food);

                    program.drawSpecialFood(bonusfood, randomNumbersGenerator, eatenTimes);

                    lastFoodTime = Environment.TickCount;
                    sleepTime--;

                    ///<summary>
                    /// Create new obstacle in new position.
                    /// </summary>
                    Position obstacle = new Position();
                    do
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                                randomNumbersGenerator.Next(4, Console.WindowWidth));
                    }
                    ///<summary>
                    /// Draw the obstacle on the game screen in random position.
                    /// </summary>
                    while (snakeElements.Contains(obstacle) ||
                           obstacles.Contains(obstacle) ||
                           (food.row != obstacle.row && food.col != obstacle.row));
                    obstacles.Add(obstacle);
                    Console.SetCursorPosition(obstacle.col, obstacle.row);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("▒");
                }
                else if (snakeNewHead.col == bonusfood.col && snakeNewHead.row == bonusfood.row)
                {
                    eatenTimes++;
                    bonus += 100;

                    if (eatenTimes == 2)
                    {
                        lvlNum++;
                        program.displayLevel(lvlNum);
                        foodDissapearTime = 8000;
                    }

                    if (eatenTimes == 3)
                    {
                        lvlNum++;
                        program.displayLevel(lvlNum);
                        foodDissapearTime = 7000;
                    }

                    if (eatenTimes == 4)
                    {
                        lvlNum++;
                        program.displayLevel(lvlNum);
                        foodDissapearTime = 6000;
                    }

                    if (eatenTimes == 5)
                    {
                        lvlNum++;
                        program.displayLevel(lvlNum);
                    }

                    program.winGame(negativePoints, eatenTimes, snakeElements, bonus, lvlNum);

                    lastFoodTime = Environment.TickCount;
                    sleepTime--;

                    ///<summary>
                    /// Create new obstacle in new position.
                    /// </summary>
                    Position obstacle = new Position();
                    do
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                                randomNumbersGenerator.Next(4, Console.WindowWidth));
                    }
                    ///<summary>
                    /// Draw the obstacle on the game screen in random position.
                    /// </summary>
                    while (snakeElements.Contains(obstacle) ||
                           obstacles.Contains(obstacle) ||
                           (food.row != obstacle.row && food.col != obstacle.row));
                    obstacles.Add(obstacle);
                    Console.SetCursorPosition(obstacle.col, obstacle.row);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("▒");
                }
                else
                {
                    // moving...
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(" ");
                    program.displayScore(snakeElements, negativePoints, bonus);
                }

                ///<summary>
                /// Calculation of negative points when the snake miss the food.
                /// </summary>
                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints = negativePoints + 50;

                    if (negativePoints >= 200)
                    {
                        program.gameOver(snakeElements, negativePoints, bonus, lvlNum);
                    }

                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write("  ");
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(4, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    lastFoodTime = Environment.TickCount;
                }

                program.drawFood(food);

                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            //backgorund sound is played when the player start the game
            SoundPlayer player = new SoundPlayer();

            player.SoundLocation = AppDomain.CurrentDomain.BaseDirectory + "/mainmenu.wav";
            player.Play();

            byte right             = 0;
            byte left              = 1;
            byte down              = 2;
            byte up                = 3;
            int  lastFoodTime      = 0;
            int  foodDissapearTime = 12000;
            int  negativePoints    = 0;
            int  winningscore      = 100;
            int  _scorecount       = 0;

            Console.WriteLine("Name: ");
            string winner = Console.ReadLine();

            if (File.Exists("winner.txt") == true)
            {
                string previouswinner = File.ReadAllText("winner.txt");
                Scoreboard.WriteAt("Previous Winner: " + previouswinner, 0, 0);
            }
            else if (File.Exists("winner.txt") == false)
            {
                File.Create("winner.txt");
            }
            File.WriteAllText("winner.txt", winner + " with score " + _scorecount);
            Scoreboard.WriteAt("Your Current Score", 0, 1);
            Scoreboard.WriteScore(_scorecount, 0, 2);


            //Array which is a linear data structure is used
            //position store direction (array)
            Position[] directions = new Position[]
            {
                new Position(0, 1),     // right
                new Position(0, -1),    // left
                new Position(1, 0),     // down
                new Position(-1, 0),    // up
            };
            double sleepTime = 100;
            int    direction = right;
            Random randomNumbersGenerator = new Random();

            Console.BufferHeight = Console.WindowHeight;

            //Linked List which is a linear data structure is used
            //Creating a linkedlist
            //Using List class
            //list to store position of obstacles
            //The obstacles are randomizd so it will appear randomly everytime user play it
            List <Position> obstacles = new List <Position>()
            {
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth))
            };

            //For each loop
            //Each obstacle in List(obstacles) to set the color, position
            //Print out the obstacle
            foreach (Position obstacle in obstacles)
            {
                //drawing obstacles
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.SetCursorPosition(obstacle.col, obstacle.row);
                Console.Write("=");
            }

            //creating snake body (5 "*")
            //Queue which is a linear data structure is used
            //Queue is like a container
            //Enqueue is implementation of Queue to insert new element at the rear of the queue
            //Set 5 items in snakeElements by setting the position (0,i)
            //i increase every time until 5
            //snakeElements used to store the snake body elements (*)
            //Reduce the body length of snake to 3 units of *
            Queue <Position> snakeElements = new Queue <Position>();

            for (int i = 0; i <= 3; i++)
            {
                snakeElements.Enqueue(new Position(5, i));
            }

            //The position is create randomly
            //creating food in the game
            Position food = new Position();

            food         = CreateFood(food, randomNumbersGenerator, snakeElements, obstacles);
            lastFoodTime = Environment.TickCount;

            //drawing snake body ("*")
            //set color and position of each of the part of body in snakeElements
            foreach (Position position in snakeElements)
            {
                Console.SetCursorPosition(position.col, position.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");
            }

            //The following code will run until the program stop
            while (true)
            {
                negativePoints++;

                //the movement of the snake
                //When the user click the arrow key, if the snake direction is not same,
                //it will change the snake direction
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userInput = Console.ReadKey();
                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        if (direction != right)
                        {
                            direction = left;
                        }
                    }
                    if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        if (direction != left)
                        {
                            direction = right;
                        }
                    }
                    if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        if (direction != down)
                        {
                            direction = up;
                        }
                    }
                    if (userInput.Key == ConsoleKey.DownArrow)
                    {
                        if (direction != up)
                        {
                            direction = down;
                        }
                    }
                }

                //manage the position of the snake head if the snake exceed the width or height of the console window
                //if the snake disappear at the bottom, it will reappear from the top
                Position snakeHead     = snakeElements.Last();
                Position nextDirection = directions[direction];

                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 < 3 && snakeNewHead.col < 40)
                {
                    snakeNewHead.col = 0;
                    snakeNewHead.row = 5;
                    direction        = right;
                }
                if (snakeNewHead.row >= Console.WindowHeight)
                {
                    snakeNewHead.row = 0;
                }
                if (snakeNewHead.col >= Console.WindowWidth)
                {
                    snakeNewHead.col = 0;
                }

                //the game will over if the snake eat its body OR eat the obstacles
                //Stack which is a linear data structure is used
                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                {
                    File.WriteAllText("winner.txt", winner + " with score " + _scorecount);
                    //Game over sound will display if the snake die
                    SoundPlayer player1 = new SoundPlayer();
                    player1.SoundLocation = AppDomain.CurrentDomain.BaseDirectory + "/die.wav";
                    player1.PlaySync();

                    //displayed when game over
                    //------------------------------------------------GameOver----------------------------------------------------
                    Console.ForegroundColor = ConsoleColor.Red;
                    string gameover = "Game over!";
                    string points   = "Your points are: ";
                    string exit     = "Press Enter to exit.";
                    int    height   = decimal.ToInt32((Console.WindowHeight) / 2) - 3;
                    int    width    = decimal.ToInt32((Console.WindowWidth - gameover.Length) / 2);

                    //print Game over and points
                    height = PrintAtCenter(gameover, height);
                    height = PrintAtCenter(points + _scorecount, height);

                    //------------------------------------------------Exit Game----------------------------------------------------

                    //Print Exit Game
                    height = PrintAtCenter(exit, height);

                    //Make a loop until user press enter key to exit the game
                    while (Console.ReadKey().Key != ConsoleKey.Enter)
                    {
                        height = PrintAtCenter(exit, height);
                    }
                    Environment.Exit(0);
                }

                //Set the position of the snake
                Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");

                //draw the snake head according to different direction
                snakeElements.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                Console.ForegroundColor = ConsoleColor.Gray;
                if (direction == right)
                {
                    Console.Write(">");
                }
                if (direction == left)
                {
                    Console.Write("<");
                }
                if (direction == up)
                {
                    Console.Write("^");
                }
                if (direction == down)
                {
                    Console.Write("v");
                }

                //when the snake eat the food
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                {
                    _scorecount += 1;
                    Scoreboard.WriteAt("Your Current Score", 0, 1);
                    Scoreboard.WriteScore(_scorecount, 0, 2);

                    if (_scorecount == winningscore)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        string gamewon = "You have won the game!";
                        int    height  = decimal.ToInt32((Console.WindowHeight) / 2);
                        int    width   = decimal.ToInt32((Console.WindowWidth - gamewon.Length) / 2);

                        Console.SetCursorPosition(width, height);
                        Console.WriteLine("You have won the game!");
                        Console.SetCursorPosition(width, height + 1);
                        Console.WriteLine("Your points are: " + _scorecount);

                        Console.WriteLine("Winner saved into text file!");
                        File.WriteAllText("winner.txt", winner + " with score " + _scorecount);
                        string previouswinner = File.ReadAllText("winner.txt");
                        Console.WriteLine(previouswinner);

                        Console.WriteLine("Press Enter to exit.");

                        while (Console.ReadKey().Key != ConsoleKey.Enter)
                        {
                            Console.WriteLine("Press Enter to exit.");
                        }
                        Environment.Exit(0);
                    }
                    //feeding the snake
                    //generate new position for the food
                    food         = CreateFood(food, randomNumbersGenerator, snakeElements, obstacles);
                    lastFoodTime = Environment.TickCount;
                    sleepTime--;

                    Position obstacle = new Position();
                    //generate new position for the obstacles
                    obstacle = CreateObstacle(food, obstacle, randomNumbersGenerator, snakeElements, obstacles);
                }
                else
                {
                    // moving...if didn't meet the conditions above then the snake will keep moving
                    Position last = snakeElements.Dequeue();
                    //The snake position will be set to the begining of the snakeElements
                    //“Dequeue” which is used to remove and return the begining object
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(" ");
                }

                //If the food appear at the console window (whole game time minus time of last food)
                //is greater than the foodDissapearTime which intialise is 8000

                //----------------------------------------------FoodRelocateTime--------------------------------------------------

                //add another 5000 time to extend the food relocate time
                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints = negativePoints + 50;
                    Console.SetCursorPosition(food.col, food.row); //the cursor position will set to the food position.
                    Console.Write(" ");

                    food         = CreateFood(food, randomNumbersGenerator, snakeElements, obstacles);
                    lastFoodTime = Environment.TickCount; //The lastFoodTime will reset to the present time
                }

                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }