Exemplo n.º 1
0
        private static bool MoveSnake(Queue <Point> snake, Point targetPosition,
                                      int snakeLength, Size screenSize)
        {
            var lastPoint = snake.Last();

            if (lastPoint.Equals(targetPosition))
            {
                return(true);
            }

            if (snake.Any(x => x.Equals(targetPosition)))
            {
                return(false);
            }

            if (targetPosition.X < 0 || targetPosition.X >= screenSize.Width ||
                targetPosition.Y < 0 || targetPosition.Y >= screenSize.Height)
            {
                return(false);
            }

            Console.BackgroundColor = ConsoleColor.Green;
            Console.SetCursorPosition(lastPoint.X + 1, lastPoint.Y + 1);
            Console.WriteLine(" ");

            snake.Enqueue(targetPosition);

            Console.BackgroundColor = ConsoleColor.Red;
            Console.SetCursorPosition(targetPosition.X + 1, targetPosition.Y + 1);
            Console.Write(" ");

            // Quitar cola
            if (snake.Count > snakeLength)
            {
                var removePoint = snake.Dequeue();
                Console.BackgroundColor = ConsoleColor.Black;
                Console.SetCursorPosition(removePoint.X + 1, removePoint.Y + 1);
                Console.Write(" ");
            }
            return(true);
        }
Exemplo n.º 2
0
        private static Point ShowFood(Size screenSize, Queue <Point> snake)
        {
            var foodPoint = Point.Empty;
            var snakeHead = snake.Last();
            var rnd       = new Random();

            do
            {
                var x = rnd.Next(0, screenSize.Width - 1);
                var y = rnd.Next(0, screenSize.Height - 1);
                if (snake.All(p => p.X != x || p.Y != y) &&
                    Math.Abs(x - snakeHead.X) + Math.Abs(y - snakeHead.Y) > 8)
                {
                    foodPoint = new Point(x, y);
                }
            } while (foodPoint == Point.Empty);

            Console.BackgroundColor = ConsoleColor.Blue;
            Console.SetCursorPosition(foodPoint.X + 1, foodPoint.Y + 1);
            Console.Write(" ");

            return(foodPoint);
        }
Exemplo n.º 3
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;
            int      lastBonusFoodTime = 0;
            //The food relocate's timer (adjusted)
            int    foodDissapearTime      = 15000;
            int    BonusFoodDisappearTime = 9000;
            int    negativePoints         = 0;
            int    userPoints             = 0;
            double sleepTime = 100;
            //Snake contain three lives
            int snakeLives = 3;


            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.Clear();
                string   lines = File.ReadAllText("Score.txt");
                string[] items = lines.Split(' ', '\n');


                int n = items.Length;
                for (int i = 1; i < n - 1; i += 2)
                {
                    int key = int.Parse(items[i]);
                    int j   = i - 2;

                    while (j >= 0 && int.Parse(items[j]) < key)
                    {
                        items[j + 2] = items[j];
                        j            = j - 2;
                    }
                    items[j + 2] = key.ToString();
                }


                for (int x = 0; x < n - 1; x += 2)
                {
                    Console.WriteLine("Name = {0}, Score = {1}",
                                      items[x], items[x + 1]);
                }

                Console.ReadLine();
            }
            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);

            Position BonusFood;

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

            game1.createBonusFood(BonusFood);

            //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 to display the snake lives.
                Console.SetCursorPosition(100, 0);
                Console.ForegroundColor = ConsoleColor.White;
                snakeLives = Math.Max(snakeLives, 0);
                Console.WriteLine("Snake lives left: {0} \t", snakeLives);

                //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))
                {
                    snakeLives--;
                }
                else if (userPoints >= 10) //winning condition
                {
                    //This sound plays when the player wins
                    SoundPlayer sound2 = new SoundPlayer("gamestart.wav");
                    sound2.Play();

                    string player_name = game1.gameWon();

                    using (StreamWriter file = new StreamWriter("Score.txt", true))
                    {
                        file.WriteLine(player_name + " " + userPoints);
                    }
                    return;
                }
                if (snakeLives == 0 || (snakeNewHead.col < 0) || (snakeNewHead.row < 0) || (snakeNewHead.row >= Console.WindowHeight) || (snakeNewHead.col >= Console.WindowWidth))
                {
                    //This is to display the snake lives.
                    Console.SetCursorPosition(100, 0);
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("Snake lives left: 0 ");

                    SoundPlayer sound1 = new SoundPlayer("die.wav");
                    sound1.Play();

                    string player_name = game1.gameOverScreen(userPoints, snakeLives);

                    using (StreamWriter file = new StreamWriter("Score.txt", true))
                    {
                        file.WriteLine(player_name + " " + userPoints);
                    }
                    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);
                }
                // snake eat bonus food
                else if (snakeNewHead.col == BonusFood.col && snakeNewHead.row == BonusFood.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 += 2;

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

                    lastBonusFoodTime = Environment.TickCount;
                    game1.createBonusFood(BonusFood);
                    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) || (BonusFood.row != obstacle.row && BonusFood.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);

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

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            byte right             = 0;
            byte left              = 1;
            byte up                = 2;
            byte down              = 3;
            int  lastFoodTime      = 0;
            int  foodDissapearTime = 8000;
            int  negativePoints    = 0;

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

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

            List <Position> obsticles = new List <Position>()
            {
                new Position(12, 12),
                new Position(15, 30),
                new Position(7, 14),
            };

            foreach (var obstucle in obsticles)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.SetCursorPosition(obstucle.col, obstucle.row);
                Console.Write("X");
            }

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

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

            Position food;

            do
            {
                food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth));
            }while (snakeEl.Contains(food) || obsticles.Contains(food));
            Console.SetCursorPosition(food.col, food.row);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("@");

            foreach (Position position in snakeEl)
            {
                Console.SetCursorPosition(position.col, position.row);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("*");
            }

            while (true)
            {
                negativePoints++;

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

                Position snakeHead     = snakeEl.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;
                }

                /*(snakeNewHead.row < 0 || snakeNewHead.col < 0 || snakeNewHead.row >= Console.WindowHeight || snakeNewHead.col >= Console.WindowWidth || */
                if (snakeEl.Contains(snakeNewHead) || obsticles.Contains(snakeNewHead))
                {
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Game Over!");
                    int userPoints = ((snakeEl.Count - 6) * 100) - negativePoints;
                    userPoints = Math.Max(userPoints, 0);
                    Console.WriteLine($"Your point are: {userPoints}");
                    return;
                }


                Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("*");

                snakeEl.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                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)
                {
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeEl.Contains(food) || obsticles.Contains(food));
                    lastFoodTime = Environment.TickCount;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("@");
                    sleepTime--;

                    Position obsticle = new Position();
                    do
                    {
                        obsticle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeEl.Contains(obsticle) || obsticles.Contains(obsticle) || food.row != obsticle.row && food.col != food.col);
                    obsticles.Add(obsticle);
                    Console.SetCursorPosition(obsticle.col, obsticle.row);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("X");
                }
                else
                {
                    Position last = snakeEl.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 (snakeEl.Contains(food));
                    lastFoodTime = Environment.TickCount;
                }

                Console.SetCursorPosition(food.col, food.row);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("@");

                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Main starts here
        /// </summary>
        //Define direction by using index number
        //Set the time taken for the food to be dissappear
        //Initialise negative points
        static void Main(string[] args)
        {
            byte right                    = 0;
            byte left                     = 1;
            byte down                     = 2;
            byte up                       = 3;
            int  lastFoodTime             = 0;
            int  foodDissapearTime        = 10000; //food dissappears after 10 second
            int  powerUpDissapearTime     = 5000;
            int  lastPowerUpDissapearTime = 0;
            int  powerUpAppearTime        = 2000;
            int  lastPowerUpAppearTime    = 0;


            int    life             = 3;
            int    userPoints       = 0;
            int    finalScore       = 0;
            int    dieCountDownTime = 150; //Time limit per life in seconds
            double sleepTime        = 100;
            int    numofObstacles   = 0;
            string userName         = "******";
            int    lifeBonusPoint   = 0; //Life bonus point is bonus point added in winning condition with per life left
            string selectedMode;

            Console.SetWindowSize(80, 30);//reducing screen size
            Console.SetBufferSize(Console.WindowWidth, Console.WindowHeight);


            Position[] directions = new Position[4];

            Program p = new Program();

            //disbale the resize of console window by disabling maximize button and border dragging
            DeleteMenu(GetSystemMenu(GetConsoleWindow(), false), maximizeButton, console);
            DeleteMenu(GetSystemMenu(GetConsoleWindow(), false), consoleBorder, console);



            //Main menu snake console ASCII ART is here
            int DA = 0;
            int V  = 255;
            int ID = 0;

            for (int i = 0; i < 1; i++)
            {
                Console.WriteAscii("SNAKE", Color.FromArgb(DA, V, ID));
            }

            //Console snake size set with BufferArea using new library
            Console.MoveBufferArea(0, 0, Console.BufferWidth, Console.BufferHeight, 22, 5);

            //Game mode menu for bound and unbound
            List <string> modeMenu = new List <string>()
            {
                "Bound Mode",
                "Unbound Mode"
            };


            while (true)
            {
                selectedMode = drawModeMenu(modeMenu);
                if (selectedMode == "Bound Mode")
                {
                    if (Console.ReadKey().Key == ConsoleKey.Enter)
                    {
                        break;
                    }
                }
                else if (selectedMode == "Unbound Mode")
                {
                    if (Console.ReadKey().Key == ConsoleKey.Enter)
                    {
                        break;
                    }
                }
            }
            Console.Clear();

            //Game level snake ASCII art for screen
            Console.WriteAscii("SNAKE", Color.FromArgb(DA, V, ID));

            //Console snake size set with BufferArea using new library
            Console.MoveBufferArea(0, 0, Console.BufferWidth, Console.BufferHeight, 22, 5);

            // game menu items for level of intensity
            List <string> menuItems = new List <string>()
            {
                "Easy",
                "Medium",
                "Hard"
            };

            //display start screen before background music and game start
            p.DisplayStartScreen();
            Console.CursorVisible = false;
            while (true)
            {
                string selectedMenuItem = drawMenu(menuItems);
                if (selectedMenuItem == "Easy")
                {
                    //food disappear time to 20sec
                    //Player life = 3
                    //Game speed is 100
                    //Obstacles normal
                    foodDissapearTime = 20000;
                    life           = 3;
                    lifeBonusPoint = 200;
                    sleepTime      = 100;
                    numofObstacles = 1;
                    if (Console.ReadKey().Key == ConsoleKey.Enter)
                    {
                        break;
                    }
                }
                else if (selectedMenuItem == "Medium")
                {
                    //food disappear time to 14sec
                    //Player life = 2
                    //Game speed is 90 millisec
                    //Obstacles medium
                    foodDissapearTime = 14000;
                    life           = 2;
                    lifeBonusPoint = 400;
                    sleepTime      = 90;
                    numofObstacles = 2;
                    if (Console.ReadKey().Key == ConsoleKey.Enter)
                    {
                        break;
                    }
                }

                else if (selectedMenuItem == "Hard")
                {
                    //food disappear time to 10sec
                    //Player life = 1
                    //Game speed is 60m
                    //Obstacles hard
                    foodDissapearTime = 10000;
                    life           = 1;
                    lifeBonusPoint = 1000;
                    sleepTime      = 60;
                    numofObstacles = 4;
                    if (Console.ReadKey().Key == ConsoleKey.Enter)
                    {
                        break;
                    }
                }
            }
            Console.Clear(); // Clear console here for mode
                             //move the text for mode to center
                             //put heading on top (SNAKE)
                             //Highest score on main screen


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

            while (life > 0)
            {
                //Set the game start time everytime the player start a new game with new life
                int gameStartTime = Environment.TickCount;
                int powerUpEaten  = 0;
                int appearFlag    = 1;
                lastPowerUpAppearTime = Environment.TickCount;
                //Play background music
                p.BackgroundMusic();
                int numberFoodEaten = 0;//Initialised number of food eaten by the snake to be 0
                int negativePoints  = 0;
                //Clear the console everytime start the game in new life
                Console.Clear();
                //Print the current life point
                p.PrintLifePoint(life);

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

                Position powerUp = new Position();
                powerUp.col = 200;
                powerUp.row = 100;

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

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

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

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

                while (true)
                {
                    //Print the food count down timer
                    p.PrintFoodCountDownTimer(lastFoodTime, foodDissapearTime);
                    //Print the time left for the game
                    p.PrintDieTime(gameStartTime, dieCountDownTime);
                    //Print the accumulated score so far from the previous life game
                    p.PrintAccumulatedScore(finalScore);
                    //Print the number of food eaten by the player
                    p.PrintNumberFoodEaten(numberFoodEaten);

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

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

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

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

                    // Unbound mode selected then utilise this function
                    if (selectedMode == "Unbound Mode")
                    {
                        if (snakeNewHead.col < 0)
                        {
                            snakeNewHead.col = Console.WindowWidth - 1;
                        }
                        if (snakeNewHead.row < 2)
                        {
                            snakeNewHead.row = Console.WindowHeight - 1;
                        }
                        if (snakeNewHead.row >= Console.WindowHeight)
                        {
                            snakeNewHead.row = 2;
                        }
                        if (snakeNewHead.col >= Console.WindowWidth)
                        {
                            snakeNewHead.col = 0;
                        }
                    }



                    //print realtime user points
                    p.PrintUserPoint(ref userPoints, snakeElements, negativePoints, powerUpEaten);

                    //Check for GameOver Criteria including the Final Game Over and Die Condition
                    int gameOver = p.GameOverCheck(dieCountDownTime, gameStartTime, snakeElements, snakeNewHead, negativePoints, obstacles, ref userPoints, ref finalScore, ref life, userName);
                    if (gameOver == 1)
                    {
                        break;
                    }


                    //Check for Winning Criteria
                    int winning = p.WinningCheck(numberFoodEaten, negativePoints, ref userPoints, ref finalScore, life, userName, lifeBonusPoint);
                    if (winning == 1)
                    {
                        return;
                    }

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

                    //Snake head shape when the user presses the key to change his direction
                    snakeElements.Enqueue(snakeNewHead);
                    Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                    Console.ForegroundColor = Color.Gray;
                    if (direction == right)
                    {
                        Console.Write("►");                     //Snake head when going right
                    }
                    if (direction == left)
                    {
                        Console.Write("◄");                   //Snake head when going left
                    }
                    if (direction == up)
                    {
                        Console.Write("▲");                 //Snake head when going up
                    }
                    if (direction == down)
                    {
                        Console.Write("▼");                   //Snake head when going down
                    }
                    if ((Environment.TickCount - lastPowerUpAppearTime) > powerUpAppearTime && appearFlag == 1)
                    {
                        p.GeneratePowerUp(ref powerUp, food, snakeElements, obstacles);
                        lastPowerUpDissapearTime = Environment.TickCount;
                        appearFlag = 0;
                    }
                    if ((Environment.TickCount - lastPowerUpDissapearTime) > powerUpDissapearTime && appearFlag == 0)
                    {
                        appearFlag = 1;
                        Console.SetCursorPosition(powerUp.col, powerUp.row);
                        Console.Write(" ");
                        powerUp.col           = 0;
                        powerUp.row           = 0;
                        lastPowerUpAppearTime = Environment.TickCount;
                    }
                    if (snakeNewHead.col == powerUp.col && snakeNewHead.row == powerUp.row)
                    {
                        powerUpEaten++;
                        Console.Beep(600, 100);// Make a sound effect when food was eaten.
                        numberFoodEaten++;
                        appearFlag            = 1;
                        powerUp.col           = 0;
                        powerUp.row           = 0;
                        lastPowerUpAppearTime = Environment.TickCount;
                    }


                    // food will be positioned randomly until they are not at the same row & column as snake head
                    if ((snakeNewHead.col == food.col && snakeNewHead.row == food.row) || (snakeNewHead.col == food.col + 1 && snakeNewHead.row == food.row))
                    {
                        if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                        {
                            Console.SetCursorPosition(food.col + 1, food.row);
                        }
                        else
                        {
                            Console.SetCursorPosition(food.col, food.row);
                        }
                        Console.Write(" ");
                        Console.Beep(600, 100); // Make a sound effect when food was eaten.
                        numberFoodEaten++;      //Increase the number count by 1 each time the snake eat the food


                        p.GenerateFood(ref food, snakeElements, obstacles, powerUp);



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

                        //Generate new obstacle
                        p.GenerateNewObstacle(ref food, snakeElements, obstacles, numofObstacles, powerUp);
                    }
                    else
                    {
                        // snake is moving
                        Position last = snakeElements.Dequeue();
                        Console.SetCursorPosition(last.col, last.row);
                        Console.Write(" ");
                    }


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

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

                    //snake moving speed increased
                    sleepTime -= 0.01;

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

            return;
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            byte left      = 1;
            byte right     = 0;
            byte down      = 2;
            byte top       = 3;
            int  points    = 0;
            int  totalTime = Environment.TickCount;
            int  speed     = 100;

            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;
            int startTime = Environment.TickCount;

            Queue <Position> snakeElements = new Queue <Position>();
            List <Position>  obstacles     = new List <Position>();
            Position         food          = CreateApple(snakeElements, obstacles);

            for (int number = 1; number <= 20; number++)
            {
                Position obstacle = CreateObstacle(snakeElements, obstacles, food);
                WriteSymbol(obstacle, 'X', "obstacle");
            }

            foreach (var obstacle in obstacles)
            {
                WriteSymbol(obstacle, 'X', "obstacle");
            }

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

            foreach (Position position in snakeElements)
            {
                WriteSymbol(position, '*', "tail");
            }
            WriteSymbol(food, '@', "food");

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

                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.Row = Console.WindowHeight - 1;
                }
                if (snakeNewHead.Col < 0)
                {
                    snakeNewHead.Col = Console.WindowWidth - 1;
                }
                if (snakeNewHead.Col >= Console.WindowWidth)
                {
                    snakeNewHead.Col = 0;
                }
                if (snakeNewHead.Row >= Console.WindowHeight)
                {
                    snakeNewHead.Row = 0;
                }

                // check if you lose the game
                if (snakeElements.Contains(snakeNewHead) ||
                    (obstacles.Contains(snakeNewHead)))
                {
                    int finalTime = Environment.TickCount;
                    int minutes   = (int)(finalTime - (double)totalTime) / 1000 / 60;
                    int sec       = (int)(finalTime - (double)totalTime) / 1000 % 60;
                    int milSec    = (finalTime - totalTime) % 60;
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Game over!");
                    Console.WriteLine($"Your points: {Math.Max(0, points)}");
                    Console.WriteLine($"You time: {minutes:d2}:{sec:d2}:{milSec:d2}m");

                    return;
                }

                // add head
                snakeElements.Enqueue(snakeNewHead);
                WriteSymbol(snakeHead, '*', "tail");

                // draw head
                Console.SetCursorPosition(snakeNewHead.Col, snakeNewHead.Row);
                Console.ForegroundColor = ConsoleColor.Blue;
                if (direction == right)
                {
                    WriteSymbol(snakeNewHead, '>', "head");
                }
                if (direction == left)
                {
                    WriteSymbol(snakeNewHead, '<', "head");
                }
                if (direction == down)
                {
                    WriteSymbol(snakeNewHead, 'v', "head");
                }
                if (direction == top)
                {
                    WriteSymbol(snakeNewHead, '^', "head");
                }

                // check if food is eaten
                if (snakeNewHead.Col == food.Col && snakeNewHead.Row == food.Row)
                {
                    food    = CreateApple(snakeElements, obstacles);
                    points += 10;
                    speed  -= 3;
                    Position obstacle = CreateObstacle(snakeElements, obstacles, food);
                    WriteSymbol(obstacle, 'X', "obstacle");
                }
                else
                {
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.Col, last.Row);
                    Console.Write(' ');
                }

                int currentTime = Environment.TickCount;
                if (Math.Abs(currentTime - startTime) >= 15000)
                {
                    Console.SetCursorPosition(food.Col, food.Row);
                    Console.Write(' ');
                    food = CreateApple(snakeElements, obstacles);
                    Position obstacle = CreateObstacle(snakeElements, obstacles, food);
                    WriteSymbol(obstacle, 'X', "obstacle");
                    startTime = Environment.TickCount;
                    speed    -= 5;
                    points--;
                }
                WriteSymbol(food, '@', "food");
                speed -= (int)(0.01 * snakeElements.Count);
                Thread.Sleep(speed);
            }
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            //adds background music to game
            var myPlayer = new System.Media.SoundPlayer();

            myPlayer.SoundLocation = @"bgmusic.wav";
            myPlayer.Play();
            myPlayer.PlayLooping();

            //Initializing variables
            byte right             = 0;
            byte left              = 1;
            byte down              = 2;
            byte up                = 3;
            int  lastFoodTime      = 0;
            int  foodDissapearTime = 15000;
            int  negativePoints    = 0;

            //A array of Position entities called directions
            //defining the direction that the snake can move
            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;
            lastFoodTime         = Environment.TickCount;

            //A list of Positions entity that contain the positions of the obstacle
            List <Position> obstacles = new List <Position>()
            {
                new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
            };

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

            //creating the snake and putting the coordinates into queue
            Queue <Position> snakeElements = new Queue <Position>();

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

            //Creating position for the food and displaying it
            //The loop continues until the food element is not in snakeElements or obstacles
            Position food;

            do
            {
                food = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                    randomNumbersGenerator.Next(0, Console.WindowWidth));
            }while (snakeElements.Contains(food) || obstacles.Contains(food));
            Console.SetCursorPosition(food.col, food.row);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("@");

            //Displaying the snake
            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 isnt equal to right it will move left
                    {
                        if (direction != right)
                        {
                            direction = left;
                        }
                    }
                    if (userInput.Key == ConsoleKey.RightArrow)                     //if right arrow click it will move to the right
                    {
                        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.col < 0)
                {
                    snakeNewHead.col = Console.WindowWidth - 1;
                }
                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;
                }

                //Displaying the score
                int userPoints = (snakeElements.Count - 6) * 100 - negativePoints;
                //if (userPoints < 0) userPoints = 0;
                Console.SetCursorPosition(0, 0);
                Console.ForegroundColor = ConsoleColor.White;
                userPoints = Math.Max(userPoints, 0);
                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                {
                    string gameover = "Game over!";
                    Console.SetCursorPosition((Console.WindowWidth - gameover.Length) / 2, (Console.WindowHeight / 2) - 4);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(gameover);



                    string statuspoint = "Your points are {0}";
                    Console.SetCursorPosition((Console.WindowWidth - statuspoint.Length) / 2, (Console.WindowHeight / 2) - 3);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(statuspoint, userPoints);
                    //Asks the user for name then the name and score will be stored in a text file
                    string enternamemsg = "Enter your name: ";
                    Console.SetCursorPosition((Console.WindowWidth - statuspoint.Length) / 2, (Console.WindowHeight / 2) - 2);
                    Console.Write(enternamemsg);
                    Console.ForegroundColor = ConsoleColor.Red;


                    string name = Console.ReadLine();
                    string LMsg = name + " " + userPoints + "\n";
                    File.AppendAllText("score.txt", LMsg);

                    string exit = "Press enter to exit";
                    Console.SetCursorPosition((Console.WindowWidth - exit.Length) / 2, (Console.WindowHeight / 2) - 1);
                    Console.WriteLine(exit);
                    Console.ReadLine();
                    return;


                    //If the userPoints is more than 500, then the user wins
                }
                else if (userPoints > 500)
                {
                    string gameover = "You win!";
                    Console.SetCursorPosition((Console.WindowWidth - gameover.Length) / 2, (Console.WindowHeight / 2) - 4);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(gameover);



                    string statuspoint = "Your points are {0}";
                    Console.SetCursorPosition((Console.WindowWidth - statuspoint.Length) / 2, (Console.WindowHeight / 2) - 3);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(statuspoint, userPoints);
                    //Asks the user for name then the name and score will be stored in a text file
                    string enternamemsg = "Enter your name: ";
                    Console.SetCursorPosition((Console.WindowWidth - statuspoint.Length) / 2, (Console.WindowHeight / 2) - 2);
                    Console.Write(enternamemsg);
                    Console.ForegroundColor = ConsoleColor.Red;


                    string name = Console.ReadLine();
                    string LMsg = name + " " + userPoints + "\n";
                    File.AppendAllText("score.txt", LMsg);

                    string exit = "Press enter to exit";
                    Console.SetCursorPosition((Console.WindowWidth - exit.Length) / 2, (Console.WindowHeight / 2) - 1);
                    Console.WriteLine(exit);
                    Console.ReadLine();
                    return;
                }

                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(">");                                     //direction for snake moving right
                }
                if (direction == left)
                {
                    Console.Write("<");                                   //direction for snake moving left and so forth
                }
                if (direction == up)
                {
                    Console.Write("^");
                }
                if (direction == down)
                {
                    Console.Write("v");
                }
                //check snakehead overlapping food position
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                {
                    // feeding the snake
                    //create new food position object until position is not overlapping snake or obstacle
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    //refresh last food eat time timer counter
                    lastFoodTime = Environment.TickCount;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("@");
                    sleepTime--;
                    //create new obstacle position object until no overlapping with snake and other obstacle
                    Position obstacle = new Position();
                    do
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(1, 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);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("=");
                }
                else
                {
                    // moving...
                    //move the snake to new postion and delete the last snake element
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(" ");
                }
                //when timer counter between eating last food is higher than default food dissapear time
                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    //decrease user score by 50 if user take too long to eat the food
                    //delete the food
                    superFood      = false;
                    negativePoints = negativePoints + 50;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write(" ");
                    //create new food position until no overlapping with obstacle and snake
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    //refresh last food eat time timer counter
                    lastFoodTime = Environment.TickCount;
                }

                //This will clear the previous score shown then display the new score
                for (int i = 0; i < 13; i++)
                {
                    Console.SetCursorPosition(i, 0);
                    Console.Write(" ");
                }
                Console.SetCursorPosition(0, 0);
                string msg = "Score: " + userPoints;
                Console.Write(msg);

                Console.SetCursorPosition(food.col, food.row);
                Console.ForegroundColor = ConsoleColor.Yellow;
                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 8
0
        //increase the length of the snake by 1
        public void AddSnake()
        {
            Position temp = new Position(snakeElements.Last().row, snakeElements.Last().col + 1);

            snakeElements.Enqueue(temp);
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            int right = 0;
            int left  = 1;
            int down  = 2;
            int up    = 3;

            Position[] directions = new Position[]
            {
                new Position(0, 1),  //right
                new Position(0, -1), //left
                new Position(1, 0),  //down
                new Position(-1, 0), //up
            };
            int    sleepTime             = 100;
            int    direction             = right; //Which is the direction now
            Random randomNumberGenerator = new Random();

            Console.BufferHeight = Console.WindowHeight;

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

            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 snakeHeadPosition    = snakeElements.Last();
                Position nextDirection        = directions[direction];
                Position snakeNewHeadPosition = new Position(snakeHeadPosition.row + nextDirection.row,
                                                             snakeHeadPosition.col + nextDirection.col);
                if (snakeNewHeadPosition.row < 0 || snakeNewHeadPosition.col < 0 ||
                    snakeNewHeadPosition.row >= Console.WindowHeight ||
                    snakeNewHeadPosition.col >= Console.WindowWidth || snakeElements.Contains(snakeNewHeadPosition))
                {
                    Console.SetCursorPosition(0, 0);
                    Console.WriteLine("Game Over");
                    Console.WriteLine($"Your points are {(snakeElements.Count()-6) * 5}");
                    return;
                }
                snakeElements.Enqueue(snakeNewHeadPosition);
                if (snakeNewHeadPosition.col == food.col && snakeNewHeadPosition.row == food.row)
                {
                    food = new Position(randomNumberGenerator.Next(0, Console.WindowHeight),
                                        randomNumberGenerator.Next(0, Console.WindowWidth));
                    sleepTime -= 4;
                }
                else
                {
                    snakeElements.Dequeue();
                }

                Console.Clear();

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

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

                Thread.Sleep(sleepTime);
            }
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            byte right             = 0;
            byte left              = 1;
            byte down              = 2;
            byte up                = 3;
            int  lastFoodTime      = 0;
            int  foodDissapearTime = 15000;

            //this is used to increment when the users missed some food (in this case 3) and the snake would lost one part
            int missedFoodCount = 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
            };
            double sleepTime = 100;
            int    direction = right;

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

            initialiseObstacles();
            initialiseSnake();
            createFood();

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


            //Below are the music packs
            MediaPlayer backgroundMusic = new MediaPlayer();//Continous background music

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


            SoundPlayer changeEffect   = new SoundPlayer(@"..\..\sounds\changePosition.wav"); //sound effect when changing directions
            SoundPlayer eatEffect      = new SoundPlayer(@"..\..\sounds\munchApple.wav");     //sound effect when eating an apple
            SoundPlayer ObstacleEffect = new SoundPlayer(@"..\..\sounds\obstacleHit.wav");    //sound effect when an obstacle is hit

            while (true)
            {
                backgroundMusic.Play();
                if (backgroundMusic.Position >= new TimeSpan(0, 1, 25))
                {
                    backgroundMusic.Position = new TimeSpan(0, 0, 0);
                }

                // Control direction of snake
                if (Console.KeyAvailable)
                {
                    changeEffect.Play();
                    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;
                        }
                    }
                }

                // Reassign snake's head after crossing border
                Position snakeHead     = snakeElements.Last(); // Head at end of queue
                Position nextDirection = directions[direction];

                // If crossed border, move to other end of the terminal
                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;
                }

                //points count
                int userPoints = (snakeElements.Count - 4);
                if (missedFoodCount == 3)
                {
                    //missed 3 food in a row, deduct 1 point, remove the tail
                    Position snakeTail = snakeElements.Dequeue();            // Head at beginning of queue (to remove when points deducted)
                    Console.SetCursorPosition(snakeTail.col, snakeTail.row); // Remove the last bit of snake.
                    Console.Write(" ");
                    missedFoodCount = 0;
                }

                // If the snake hits itself or hits the obstacles
                // added new rule which is the game ends when the snake is gone
                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead) || snakeElements.Count == 0)
                {
                    ObstacleEffect.Play();
                    Thread.Sleep(500);
                    userPoints = Math.Max(userPoints, 0);
                    string gameovertext  = "Game over!";
                    string yourpointsare = "Your points are: {0}";
                    string resultmessage;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.SetCursorPosition((Console.WindowWidth - gameovertext.Length) / 2, Console.WindowHeight / 4);
                    Console.WriteLine(gameovertext);
                    Console.SetCursorPosition((Console.WindowWidth - yourpointsare.Length) / 2, (Console.WindowHeight / 4) + 1);
                    Console.WriteLine(yourpointsare, userPoints);
                    if (userPoints >= 30)//checks if the player meets winning requirement
                    {
                        resultmessage = "Congratulation! You've won the game :D";
                        Console.SetCursorPosition((Console.WindowWidth - resultmessage.Length) / 2, (Console.WindowHeight / 4) + 2);
                        Console.WriteLine(resultmessage);
                    }
                    else
                    {
                        resultmessage = "Sorry, you've lost :(";
                        Console.SetCursorPosition((Console.WindowWidth - resultmessage.Length) / 2, (Console.WindowHeight / 4) + 2);
                        Console.WriteLine(resultmessage);
                        Console.SetCursorPosition((Console.WindowWidth - 33) / 2, (Console.WindowHeight / 4) + 3);
                        Console.WriteLine("Reach 30 Points next time to win");
                    }
                    //save the score into text file
                    UpdateScores(userPoints);
                    // Pause screen
                    Console.SetCursorPosition((Console.WindowWidth - 33) / 2, (Console.WindowHeight / 4) + 6);
                    Console.WriteLine("Please ENTER key to exit the game.");
                    Console.ReadLine();
                    //! Pause screen
                    return;
                }
                else
                {
                    //reset score display
                    Console.SetCursorPosition(0, 0);
                    Console.WriteLine("Current points:              ");
                    //display score
                    Console.SetCursorPosition(0, 0);
                    Console.WriteLine("Current points: {0}", userPoints);
                }

                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 snake consumes the food:
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                {
                    eatEffect.Play();
                    createFood();
                    // feeding the snake
                    lastFoodTime = Environment.TickCount;  // Reset last food Time
                    sleepTime--;
                    //reset missedFoodCount = 0 when the snake consume the food
                    missedFoodCount = 0;

                    // Generate 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);
                    Console.SetCursorPosition(obstacle.col, obstacle.row);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("=");
                }
                else
                {
                    // moving...
                    Position last = snakeElements.Dequeue();  // Remove the last bit of snake.
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(" ");
                }

                // If food not consumed before time limit, generate new food.
                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    //Additional missed food
                    missedFoodCount++;
                    //negativePoints = negativePoints + 50;  // Additional negative points (no needed as the snake is shorter)
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write(" ");
                    createFood();
                    lastFoodTime = Environment.TickCount;
                }

                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            byte right          = 0;
            byte left           = 1;
            byte down           = 2;
            byte up             = 3;
            int  lastFoodTime   = 0;
            int  negativePoints = 0;
            int  life           = 3;
            int  userPoint;
            int  checkPoint = 200;
            bool gameFinish = false;

            //Background music
            SoundPlayer player = new SoundPlayer();

            player.SoundLocation = AppDomain.CurrentDomain.BaseDirectory + "\\Waltz-music-loop.wav";



            //max - Creates an array that has four directions
            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;
            lastFoodTime         = Environment.TickCount;

            Console.WriteLine("Please enter your name:");
            string name = Console.ReadLine();


            //add menu
            menu();
            Console.Clear();

            int multiplier        = Int32.Parse(Difficulty);
            int foodDissapearTime = 18000 - (2800 * multiplier);

            //randomise obstacles
            List <Position> obstacles = new List <Position>();


            for (int i = 0; i < 5; i++)
            {
                obstacles.Add(new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)));
            }

            //max - Setting the color, position and the 'symbol' (which is '=') of the obstacle.
            foreach (Position obstacle in obstacles)
            {
                SetObstacle(obstacle);
            }

            //create body
            Queue <Position> snakeElements = new Queue <Position>();

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

            //randomise food
            Position food;

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

            foreach (Position position in snakeElements)
            {
                SetSnakeElement(position);
            }

            //ben - create an infinite loop for user input to change the direction
            while (true)
            {
                negativePoints++;

                userPoint = (snakeElements.Count - 4) * 120 - negativePoints;
                if (userPoint < 0)
                {
                    userPoint = 0;
                }
                userPoint = Math.Max(userPoint, 0);
                Console.SetCursorPosition(0, 0);
                Console.Write("Score:{0}" + "          ", userPoint);
                Console.SetCursorPosition(17, 0);
                Console.Write("|");
                Console.SetCursorPosition(0, 1);
                Console.WriteLine("Lifes:{0}" + "          ", life);
                Console.SetCursorPosition(17, 1);
                Console.Write("|");
                Console.SetCursorPosition(17, 2);
                Console.Write("|");
                Console.SetCursorPosition(0, 2);
                Console.Write("Next life at:{0} ", checkPoint);
                Console.SetCursorPosition(0, 3);
                Console.WriteLine("_________________|");

                if (Console.KeyAvailable)
                {
                    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;
                        }
                    }
                }

                //philip - Snakeelements' last array number will be the snakeHead's position.
                Position snakeHead = snakeElements.Last();
                //nextDirection's value will be the direction's that is input by the user.
                Position nextDirection = directions[direction];
                //snakeNewHead will be using the if statement at line after 122 to calculate and get the result.
                Position snakeNewHead = new Position(snakeHead.row + nextDirection.row,
                                                     snakeHead.col + nextDirection.col);

                //max - allows the snake to appear at the bottom when the snake moves out of the top border vertically
                if (snakeNewHead.col < 18 && snakeNewHead.row < 4 && direction == left)
                {
                    snakeNewHead.col = Console.WindowWidth - 1;
                }
                if (snakeNewHead.col < 0)
                {
                    snakeNewHead.col = Console.WindowWidth - 1;
                }
                //max - allows the snake to appear on the right side when the snake moves out of the left border horizontally
                if (snakeNewHead.col < 18 && snakeNewHead.row < 4 && direction == up)
                {
                    snakeNewHead.row = Console.WindowHeight - 1;
                }
                if (snakeNewHead.row < 0)
                {
                    snakeNewHead.row = Console.WindowHeight - 1;
                }
                //max - allows the snake to appear on the left side when the snake moves out of the right border horizontally
                if (snakeNewHead.row >= Console.WindowHeight && snakeNewHead.col < 18)
                {
                    snakeNewHead.row = 4;
                }
                if (snakeNewHead.row >= Console.WindowHeight)
                {
                    snakeNewHead.row = 0;
                }
                //max - allows the snake to appear at the top when the snake moves out of the bottom border vertically
                if (snakeNewHead.col >= Console.WindowWidth && snakeNewHead.row < 4)
                {
                    snakeNewHead.col = 18;
                }
                if (snakeNewHead.col >= Console.WindowWidth)
                {
                    snakeNewHead.col = 0;
                }


                //ben - if snake head is collide with the body, decrease 1 life
                if (obstacles.Contains(snakeNewHead))
                {
                    life--;
                    // add life
                    if (life != 0)
                    {
                        negativePoints += 50;
                        //everymultiplier the snake consume an obstacle this function will add another new one
                        foreach (Position obstacle in obstacles.ToList())
                        {
                            if (obstacle.col == snakeNewHead.col && obstacle.row == snakeNewHead.row)
                            {
                                obstacles.Remove(obstacle);
                            }
                        }

                        AddNewObstacle();
                    }

                    else
                    {
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("Lifes:{0}", life);
                        Lose();
                        return;
                    }
                }

                // if snake eat his body, minus 1 live, decrease 1 element, and decrease the score
                if (snakeElements.Contains(snakeNewHead))
                {
                    life--;
                    if (life != 0)
                    {
                        negativePoints += 50;
                        Position last = snakeElements.Dequeue();
                        Console.SetCursorPosition(last.col, last.row);
                        Console.Write(" ");
                    }

                    else
                    {
                        Console.SetCursorPosition(0, 1);
                        Console.WriteLine("Lifes:{0}", life);
                        player.Stop();
                        Lose();
                        return;
                    }
                }

                //philip - Base on where the snakehead's position,produce gray color * for the snake body
                Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");

                //max - Add the 'snakeNewHead' to the queue
                snakeElements.Enqueue(snakeNewHead);
                //max - Set the position of the snakeNewHead
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                //max - set the color of the snake head
                Console.ForegroundColor = ConsoleColor.Gray;
                //max - controls the direction of the snake
                if (direction == right)
                {
                    Console.Write(">");
                }
                if (direction == left)
                {
                    Console.Write("<");
                }
                if (direction == up)
                {
                    Console.Write("^");
                }
                if (direction == down)
                {
                    Console.Write("v");
                }

                //ben - if snake head reached the food, the snake elements increase by 1 and add a new food and an obstacle.
                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(" ");

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

                    //Soundeffect added.
                    SystemSounds.Beep.Play();

                    // feeding the snake
                    AddNewFood();

                    //check current score
                    checkScore();

                    // get the lastFoodTime (in Millisecond)
                    lastFoodTime = Environment.TickCount;

                    SetFood();
                    sleepTime--;

                    for (int i = 0; i < multiplier; i++)
                    {
                        AddNewObstacle();
                    }
                }
                else
                {
                    // moving...
                    //remove the last element of the snake elements and return it to the begining
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    //replace the last element with blank
                    Console.Write(" ");
                }
                //philip - This if statement is to reposition the food's position
                //from its last location if the tickcount is more than the foodDissapearTime
                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints = negativePoints + 50;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write(" ");
                    AddNewFood();
                    lastFoodTime = Environment.TickCount;
                }

                SetFood();

                //Add winning requirement
                if (snakeElements.Count == multiplier * 20)
                {
                    Win();
                    return;
                }

                sleepTime -= 0.01;
                Thread.Sleep((int)sleepTime);
            }

            // set the food postion,color,icon.
            void SetFood()
            {
                Console.SetCursorPosition(food.col, food.row);
                Console.ForegroundColor = ConsoleColor.Yellow;
                //set the food to black heart
                string cUnicode = "2665";
                int    value    = int.Parse(cUnicode, System.Globalization.NumberStyles.HexNumber);
                string symbol   = char.ConvertFromUtf32(value).ToString();
                string foode    = symbol + symbol;

                Console.OutputEncoding = System.Text.Encoding.Unicode;
                Console.Write(foode);
            };

            // set the obstacle position,color,icon.
            void SetObstacle(Position obstacle)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.SetCursorPosition(obstacle.col, obstacle.row);
                //set the obstacle to medium shade
                string cUnicode = "2592";
                int    value    = int.Parse(cUnicode, System.Globalization.NumberStyles.HexNumber);
                string symbol   = char.ConvertFromUtf32(value).ToString();

                Console.OutputEncoding = System.Text.Encoding.Unicode;
                Console.Write(symbol);
            }

            //set the snake element postion,color,icon
            void SetSnakeElement(Position position)
            {
                Console.SetCursorPosition(position.col, position.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");
            }

            //lose
            void Lose()
            {
                gameFinish = true;
                int    y     = Console.WindowHeight / 2;
                string text1 = "Game over!";
                string text2 = "Your points are: ";
                string text3 = "Press 1 to view leaderboard, 2 to exit the game";

                int text1length = text1.Length;
                int text2length = text2.Length;
                int text3length = text3.Length;

                int text1start = (Console.WindowWidth - text1length) / 2;
                int text2start = (Console.WindowWidth - text2length) / 2;
                int text3start = (Console.WindowWidth - text3length) / 2;

                //Set Game over to middle of the window
                Console.SetCursorPosition(text1start, y);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(text1);


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

                if (userPoints < 0)
                {
                    userPoints = 0;
                }

                //Set Score to middle of the window
                Console.SetCursorPosition(text2start, y + 1);
                userPoints = Math.Max(userPoints, 0);
                Console.WriteLine("{0}{1}", text2, userPoints);

                Console.SetCursorPosition(text3start, y + 2);
                Console.WriteLine(text3);

                //Add player score into plain text file.
                StreamWriter snakeFile = new StreamWriter("Snake_Score.txt", true);

                snakeFile.Write(name + "\n");
                snakeFile.Write(userPoints + "\n");
                snakeFile.Close();

                string input = Console.ReadLine();

                while (input != "1" && input != "2")
                {
                    Console.WriteLine("Please enter a valid number");
                    input = Console.ReadLine();
                }

                if (input == "1")
                {
                    ShowLeaderBoard(2);
                }

                else if (input == "2")
                {
                    Environment.Exit(0);
                }
            }

            void Win()
            {
                gameFinish = true;
                int    y     = Console.WindowHeight / 2;
                string text1 = "You Win!!!!";
                string text2 = "Your points are: ";
                string text3 = "Press 1 to view leaderboard, 2 to exit the game";

                int text1length = text1.Length;
                int text2length = text2.Length;
                int text3length = text3.Length;

                int text1start = (Console.WindowWidth - text1length) / 2;
                int text2start = (Console.WindowWidth - text2length) / 2;
                int text3start = (Console.WindowWidth - text3length) / 2;

                Console.SetCursorPosition(text1start, y);
                Console.WriteLine(text1);

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

                if (userPoints < 0)
                {
                    userPoints = 0;
                }

                //Set Score to middle of the window
                Console.SetCursorPosition(text2start, y + 1);
                userPoints = Math.Max(userPoints, 0);
                Console.WriteLine("{0}{1}", text2, userPoints);

                Console.SetCursorPosition(text3start, y + 2);
                Console.WriteLine(text3);

                //Add player score into plain text file.
                StreamWriter snakeFile = new StreamWriter("Snake_Score.txt", true);

                snakeFile.Write(name + "\n");
                snakeFile.Write(userPoints + "\n");
                snakeFile.Close();

                string input = Console.ReadLine();

                while (input != "1" && input != "2")
                {
                    Console.WriteLine("Please enter a valid number");
                    input = Console.ReadLine();
                }

                if (input == "1")
                {
                    ShowLeaderBoard(2);
                }

                else if (input == "2")
                {
                    Environment.Exit(0);
                }
            }

            void checkScore()
            {
                int updatePoint = userPoint + 100;

                if (updatePoint >= checkPoint)
                {
                    life++;
                    checkPoint += (500 * multiplier);
                }
            }

            void AddNewObstacle()
            {
                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) || (obstacle.col < 18 && obstacle.row < 4));
                obstacles.Add(obstacle);
                SetObstacle(obstacle);
            }

            void AddNewFood()
            {
                do
                {
                    food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth));
                }while (snakeElements.Contains(food) || obstacles.Contains(food) || (food.col < 18 && food.row < 4));
            }

            //philip
            void helpmenu()
            {
                Console.Clear();
                //Showing Guides for the Player.
                Console.WriteLine("Welcome to the Snake Game\n");
                Console.WriteLine("This Page will be guiding you how to play this game.\n");
                Console.WriteLine("The below are the symbols of the game and what are they representing\n");
                Console.WriteLine(" ***>  -  Your snake     @  - Your food     =  -  Obstacle\n");
                Console.WriteLine("The Control Keys are your Arrow Keys.\n");
                Console.WriteLine("Your snake will only move foward and you need to use your arrow keys to control its moving direction.\n");
                Console.WriteLine("The game will be having 3 lifes and 5 obstacles to start with and obstacles are randomly spawn.\n\nEach time you eat a food, which will be showing like @ symbol\n");
                Console.WriteLine("Each time you hit an Obstacle, it will disappear and respawn at a different location and you deduct one life and some scores as punishment.\n");
                Console.WriteLine("If you eat/hit your own body, you will lose directly, so please avoid that.\n");
                Console.WriteLine("There are 3 Difficulty, Easy, Normal and Hard. Details as below:\n");
                Console.WriteLine("Easy - Each 500 score will increase 1 EXTRA LIFE. Winning Requirement: Eat 20 foods\n");
                Console.WriteLine("Normal - Each 1000 score will increase 1 EXTRA LIFE. Each obstacle consume will increase 2 more obstacle and Food disappear speed is increased. Winning Requirement: Eat 40 foods\n");
                Console.WriteLine("Hard - Each 1500 score will increase 1 EXTRA LIFE. Each obstacle consume will increase 3 more obstacle and Food disappeaer speed is increase significantly. Winning Requirement: Eat 60 foods\n");
                Console.WriteLine("Your score will be recorded into the leaderboard for record everytime you WIN or Lose.\n");

                //Prompt the user to select an option after viewing leaderboard
                string userLeadInput;
                int    userLIResult = 0;
                bool   validInput   = false;

                Console.Write("\n" + "Enter '1' to go back to main menu and '2' to exit the program\n");
                userLeadInput = Console.ReadLine();

                while (!validInput)
                {
                    if (!int.TryParse(userLeadInput, out userLIResult))
                    {
                        Console.WriteLine("Please enter '1' or '2'");
                    }
                    else if (userLIResult.Equals(0))
                    {
                        Console.WriteLine("You cannot enter zero.");
                    }
                    else
                    {
                        validInput = true;
                        if (userLIResult == 1)
                        {
                            Console.Clear();
                            menu();
                        }
                        else if (userLIResult == 2)
                        {
                            Environment.Exit(0);
                        }
                    }
                }
            }

            void ShowLeaderBoard(int condition)
            {
                player.Stop();
                Console.Clear();

                string line;

                List <string> playerlist  = new List <string>();
                List <int>    scorelist   = new List <int>();
                List <string> playerlist2 = new List <string>();
                List <int>    scorelist2  = new List <int>();

                int z = 1;

                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("");
                }

                Console.ForegroundColor = ConsoleColor.White;

                System.IO.StreamReader file = new System.IO.StreamReader("Snake_Score.txt");

                int counter = 0;
                int index   = 0;

                while ((line = file.ReadLine()) != null)
                {
                    if (counter % 2 == 0)
                    {
                        playerlist.Add(line);
                    }

                    else
                    {
                        scorelist.Add(Int32.Parse(line));
                    }

                    counter++;
                }
                file.Close();

                int length = playerlist.Count();

                // find top 10 highest
                for (int i = 0; i < length; i++)
                {
                    int highest = scorelist[0];
                    index = 0;

                    for (int q = 0; q < scorelist.Count(); q++)
                    {
                        if (scorelist[q] > highest)
                        {
                            highest = scorelist[q];
                            index   = q;
                        }
                    }

                    playerlist2.Add(playerlist[index]);
                    scorelist2.Add(scorelist[index]);
                    playerlist.RemoveAt(index);
                    scorelist.RemoveAt(index);
                }

                if (length > 10)
                {
                    length = 10;
                }

                //display the leaderboard
                Console.SetCursorPosition(0, 0);
                Console.WriteLine("Leaderboard" + "\n");
                Console.WriteLine("  " + "Player" + "     " + "Score");
                Console.WriteLine("  " + "==========" + " " + "===========");
                for (int i = 0; i < length; i++)
                {
                    Console.WriteLine(z + "." + playerlist2[i] + "\t" + "\t" + scorelist2[i]);
                    z++;
                }

                if (condition == 1)
                {
                    //Prompt the user to select an option after viewing leaderboardt;
                    string userLeadInput;

                    Console.Write("\n" + "Enter '1' to go back to main menu and '2' to exit the program\n");
                    userLeadInput = Console.ReadLine();
                    while (userLeadInput != "1" && userLeadInput != "2")
                    {
                        Console.WriteLine("Please enter a valid input");
                        userLeadInput = Console.ReadLine();
                    }

                    if (userLeadInput == "1")
                    {
                        Console.Clear();
                        menu();
                    }
                    else if (userLeadInput == "2")
                    {
                        Environment.Exit(0);
                    }
                }

                else if (condition == 2)
                {
                    string userLeadInput;
                    Console.Write("\n" + "Enter anything to exit the program\n");
                    userLeadInput = Console.ReadLine();
                    Environment.Exit(0);
                }
            }

            void menu()
            {
                player.Stop();
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.White;
                string userOption;
                string condition = "correct";

                do
                {
                    int    ystart      = (Console.WindowHeight - 2) / 2;
                    string text1       = "Welcome to the Snake Menu. Please choose an option below:";
                    string text2       = "\t\t\t(1) Play Game\t(2) View Leaderboard\t(3) Help\t(4) Quit Game";
                    int    text1length = text1.Length;
                    int    text2length = text2.Length;

                    int text1start = (Console.WindowWidth - text1length) / 2;
                    int text2start = (Console.WindowWidth - text2length) / 2;

                    //Set menu to middle of the window
                    Console.SetCursorPosition(text1start, ystart);
                    Console.SetCursorPosition(text2start, ystart + 1);
                    Console.WriteLine(text1);
                    Console.WriteLine(text2);

                    userOption = Console.ReadLine();

                    switch (userOption)
                    {
                    case "1":
                        Console.WriteLine("Please select the difficulty, 1 = Easy, 2 = Medium, 3 = Hard");
                        Difficulty = Console.ReadLine();
                        while (Difficulty != "1" && Difficulty != "2" && Difficulty != "3")
                        {
                            Console.WriteLine("Please enter a valid number");
                            Difficulty = Console.ReadLine();
                        }
                        Console.WriteLine("You have chosen option " + userOption + " -> Play the game again");
                        condition = "correct";
                        player.PlayLooping();
                        break;

                    case "2":
                        Console.WriteLine("You have chosen option " + userOption + " -> View Leaderboard");
                        condition = "correct";
                        ShowLeaderBoard(1);
                        break;

                    case "3":
                        Console.WriteLine("You have chosen option " + userOption + " -> View Help Page");
                        condition = "correct";
                        helpmenu();
                        break;

                    case "4":
                        Console.WriteLine("You have chosen option" + userOption + " -> Exit the game");
                        condition = "correct";
                        Environment.Exit(0);
                        break;

                    default:
                        Console.WriteLine("Invalid user input. Please try again.\n");
                        condition = "incorrect";
                        break;
                    }
                } while (condition == "incorrect");
            }
        }
Exemplo n.º 12
0
        static void Main()
        {
            Random randomNumbersGenerator = new Random();

            Console.CursorVisible = false;
            Console.Beep();


            byte right             = 0;
            byte left              = 1;
            byte down              = 2;
            byte up                = 3;
            int  lastFoodTime      = 0;
            int  foodDissapearTime = 8000;
            int  negativePoints    = 0;

            Console.SetCursorPosition(Console.WindowWidth / 2, 0);
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write("Level 1");

            Queue <Position> snakeElements = new Queue <Position>(); // For snake growing and changing form.

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

            foreach (Position position in snakeElements) // print snake body. Col grows each iteraion
            {
                Console.SetCursorPosition(position.Col, position.Row);
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("*");
            }

            Position[] directions = new Position[] // WASD for the snake :)
            {
                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;

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

            List <Position> obstacles = new List <Position>()
            {
                //new Position(10, 40),
                //new Position(12, 40),
                //new Position(7, 7),
                //new Position(19, 19),
                //new Position(6, 9),
            };

            for (int i = 0; i <= 15; i++)
            {
                obstacles.Add(new Position(randomNumbersGenerator.Next(Console.WindowHeight),
                                           randomNumbersGenerator.Next(Console.WindowWidth)));
            }

            foreach (Position obstacle in obstacles)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.SetCursorPosition(obstacle.Col, obstacle.Row);
                Console.Write(".");
            }
            int level = 1;

            Position food = new Position();

            food = FoodChecker(food, randomNumbersGenerator, obstacles, snakeElements, level);

            PrintApple(food);

            int pointsCounter = 0;

            while (true)          // the endless[sic] cycle!!!
            {
                negativePoints++; // if an apple wasn't eaten for given foodDissapearTime time

                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();  // returns the snake head and keeps it int the variable "newHead";
                Position nextDirection = directions[direction]; // get's the element with index 'direction';

                Position snakeNewHead = new Position(snakeHead.Row + nextDirection.Row, snakeHead.Col + nextDirection.Col);

                // Go through walls
                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)) // if (snakeElements.Contains(snakeNewHead) == true)
                                                                                              // means the snake just ate her tail :D
                {
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Beep(300, 400);
                    Console.WriteLine("Game over!");

                    //if (userPoints < 0) userPoints = 0;
                    pointsCounter = (snakeElements.Count - 6) * 100; // - negativePoints;
                    pointsCounter = Math.Max(pointsCounter, 0);
                    Console.WriteLine("Your points are: {0}", pointsCounter);
                    // Console.ReadLine();
                    return;
                }

                Console.SetCursorPosition(snakeHead.Col, snakeHead.Row);
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("*");

                snakeElements.Enqueue(snakeNewHead); // MAKES THE SNAKE MOVE!!! (I hope so)
                Console.SetCursorPosition(snakeNewHead.Col, snakeNewHead.Row);
                Console.ForegroundColor = ConsoleColor.White;

                // Snake head :D
                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) // if this condition is true, then this means the snake just ate,
                                                                                  //and we have to teleport new apple and obstacle
                {
                    //feeding the snake

                    food = FoodChecker(food, randomNumbersGenerator, obstacles, snakeElements, level);

                    lastFoodTime = Environment.TickCount;  // follows the apple time before changes place
                    PrintApple(food);
                    level = LevelUp(snakeElements, level); // ...
                    sleepTime--;

                    Position obstacle = new Position();
                    while (true)
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                                randomNumbersGenerator.Next(0, Console.WindowWidth));

                        if (snakeElements.Contains(obstacle) == false || obstacles.Contains(obstacle) || // apple won't be born within the snake or obstacle!
                            (food.Row != obstacle.Row && food.Col != obstacle.Row) == false)    // might mistake with the false up.
                        {
                            break;
                        }
                    }

                    obstacles.Add(obstacle);
                    Console.SetCursorPosition(obstacle.Col, obstacle.Row);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write(".");
                }
                else
                {
                    // moving...
                    Position last = snakeElements.Dequeue();  // removes the last element and saves it
                    Console.SetCursorPosition(last.Col, last.Row);
                    Console.Write(" ");
                }

                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints += 10;
                    Console.SetCursorPosition(food.Col, food.Row);
                    Console.Write(" ");

                    while (true)
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));

                        if (snakeElements.Contains(food) == false || obstacles.Contains(food) == false)
                        {
                            break;
                        }
                    }

                    lastFoodTime = Environment.TickCount;
                }

                PrintApple(food);

                sleepTime -= 0.04;            // speed during time elapsed

                Thread.Sleep((int)sleepTime); // this function defines how much time the Console stops,
                                              // so that our eyes can see the image.
            }
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            Position[] positions = new Position[]
            {
                new Position(0, 1),  // move right
                new Position(0, -1), // move left
                new Position(1, 0),  // down
                new Position(-1, 0)  // top
            };
            int directories = 0;

            Console.BufferHeight = Console.BufferHeight;
            Queue <Position> snake = new Queue <Position>();

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

            while (true)
            {
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userInput = Console.ReadKey();
                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        directories = 1;
                    }
                    if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        directories = 0;
                    }
                    if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        directories = 3;
                    }
                    if (userInput.Key == ConsoleKey.DownArrow)
                    {
                        directories = 2;
                    }
                    if (userInput.Key == ConsoleKey.F1)
                    {
                        return;
                    }
                }

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

                Position snakeHead = snake.Last();
                snake.Dequeue();
                Position nextDirection = positions[directories];
                Position snakeNewHead  = new Position(snakeHead.row + nextDirection.row, snakeHead.col + nextDirection.col);

                snake.Enqueue(snakeNewHead);
                Console.Clear();

                foreach (Position position in snake)
                {
                    Console.SetCursorPosition(position.col, position.row);
                    Console.Write("*");
                }
                Thread.Sleep(200);
            }
        }
Exemplo n.º 14
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
            };
            int direction = 0;       //0
            int counter   = 0;

            Console.SetWindowSize(70, 40);



            Random randomNumberGenerator = new Random();

            Console.BufferHeight    = Console.WindowHeight;
            Console.BackgroundColor = ConsoleColor.White;

            Position foodD = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), randomNumberGenerator.Next(0, Console.WindowWidth));
            Position foodI = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), randomNumberGenerator.Next(0, Console.WindowWidth));
            Position foodL = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), randomNumberGenerator.Next(0, Console.WindowWidth));
            Position foodo = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), randomNumberGenerator.Next(0, Console.WindowWidth));
            Position foodg = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), randomNumberGenerator.Next(0, Console.WindowWidth));
            Position foodi = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), randomNumberGenerator.Next(0, Console.WindowWidth));
            Position foodc = new Position(randomNumberGenerator.Next(0, Console.WindowHeight), randomNumberGenerator.Next(0, Console.WindowWidth));



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

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

            Console.ForegroundColor = ConsoleColor.Green;

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


            bool food1 = true;
            bool food2 = true;
            bool food3 = true;
            bool food4 = true;
            bool food5 = true;
            bool food6 = true;
            bool food7 = true;


            while (counter < 7)
            {
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userImput = Console.ReadKey();

                    if (userImput.Key == ConsoleKey.Escape)
                    {
                        return;
                    }
                    if (userImput.Key == ConsoleKey.Enter)
                    {
                        counter = 7;
                    }

                    if (userImput.Key == ConsoleKey.LeftArrow)
                    {
                        direction = 1;
                    }
                    if (userImput.Key == ConsoleKey.RightArrow)
                    {
                        direction = 0;
                    }
                    if (userImput.Key == ConsoleKey.UpArrow)
                    {
                        direction = 3;
                    }
                    if (userImput.Key == ConsoleKey.DownArrow)
                    {
                        direction = 2;
                    }
                }
                Position snakeHead     = snakeElements.Last();
                Position nextDirection = directions[direction];
                Position snakeNewHead  = new Position(snakeHead.row + nextDirection.row, snakeHead.col + nextDirection.col);
                if (true)
                {
                    // wallsTeleport
                    if (snakeNewHead.col > Console.WindowWidth - 1)
                    {
                        snakeNewHead.col = 1;
                    }
                    if (snakeNewHead.col < 0)
                    {
                        snakeNewHead.col = Console.WindowWidth - 1;
                    }
                    if (snakeNewHead.row > Console.WindowHeight - 1)
                    {
                        snakeNewHead.row = 1;
                    }
                    if (snakeNewHead.row < 0)
                    {
                        snakeNewHead.row = Console.WindowHeight - 1;
                    }
                    //wallsTeleport
                } //wallsTeleport
                snakeElements.Enqueue(snakeNewHead);


                if (snakeNewHead.col == foodD.col && snakeNewHead.row == foodD.row)
                {
                    food1 = false;
                    counter++;
                }


                else if (snakeNewHead.col == foodI.col && snakeNewHead.row == foodI.row)
                {
                    food2 = false;
                    counter++;
                }

                else if (snakeNewHead.col == foodL.col && snakeNewHead.row == foodL.row)
                {
                    food3 = false;
                    counter++;
                }

                else if (snakeNewHead.col == foodo.col && snakeNewHead.row == foodo.row)
                {
                    food4 = false;
                    counter++;
                }

                else if (snakeNewHead.col == foodg.col && snakeNewHead.row == foodg.row)
                {
                    food5 = false;
                    counter++;
                }

                else if (snakeNewHead.col == foodi.col && snakeNewHead.row == foodi.row)
                {
                    food6 = false;
                    counter++;
                }

                else if (snakeNewHead.col == foodc.col && snakeNewHead.row == foodc.row)
                {
                    food7 = false;
                    counter++;
                }
                else
                {
                    snakeElements.Dequeue();
                }


                Console.Clear();


                Console.ForegroundColor = ConsoleColor.Green;

                foreach (Position position in snakeElements)
                {
                    Console.SetCursorPosition(position.col, position.row);
                    Console.WriteLine("*");
                }
                Console.ForegroundColor = ConsoleColor.White;



                Console.ForegroundColor = ConsoleColor.Black;

                if (food1 == true)
                {
                    Console.SetCursorPosition(foodD.col, foodD.row);
                    Console.WriteLine("D");
                }
                if (food2 == true)
                {
                    Console.SetCursorPosition(foodI.col, foodI.row);
                    Console.WriteLine("I");
                }
                if (food3 == true)
                {
                    Console.SetCursorPosition(foodL.col, foodL.row);
                    Console.WriteLine("L");
                }
                if (food4 == true)
                {
                    Console.SetCursorPosition(foodo.col, foodo.row);
                    Console.WriteLine("o");
                }
                if (food5 == true)
                {
                    Console.SetCursorPosition(foodg.col, foodg.row);
                    Console.WriteLine("g");
                }
                if (food6 == true)
                {
                    Console.SetCursorPosition(foodi.col, foodi.row);
                    Console.WriteLine("i");
                }
                if (food7 == true)
                {
                    Console.SetCursorPosition(foodc.col, foodc.row);
                    Console.WriteLine("c");
                }
                Console.ForegroundColor = ConsoleColor.White;


                Thread.Sleep(250);
            }
            Console.Clear();

            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            Console.Clear();
            Console.ResetColor();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("                        YOU WIN WITH DILOGIC !!!");
            Thread.Sleep(10000);
        }
Exemplo n.º 15
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
            };
            double sleepTime = 100;
            int    direction = right;
            Random randomNumbersGenerator = new Random();

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

            //intialise the position of first 5 obstacle
            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)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
            };

            //produce obstacles item on certain position with Cyan coloured "="
            foreach (Position obstacle in obstacles)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.SetCursorPosition(obstacle.col, obstacle.row);
                Console.Write("=");
            }

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

            do
            {
                food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                    randomNumbersGenerator.Next(0, Console.WindowWidth));
            }while (snakeElements.Contains(food) || obstacles.Contains(food));
            Console.SetCursorPosition(food.col, food.row);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("@");

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

            int userPoints = 0;

            // Loops the game till it ends
            while (true)
            {
                userPoints = (snakeElements.Count - 4) * 100 - negativePoints;
                Console.SetCursorPosition(0, 0);
                Console.ForegroundColor = ConsoleColor.Cyan;

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

                // When the user gets 500 points, the user would win
                if (userPoints >= 500)
                {
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Red;
                    string youwin = "YOU WIN!";
                    Console.WriteLine("\n\n\n\n\n\n\n\n\n\n\n");
                    Console.Write(new string(' ', (Console.WindowWidth - youwin.Length) / 2));
                    Console.WriteLine(youwin);
                    SaveScore(userName, userPoints);
                    Console.ReadLine();
                    return;
                }


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

                // When snake hits the obstacle or the snake itself, console will show "Game over!" and the total amount of points gathered
                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                {
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Red;
                    string gameover = "Game over!";
                    Console.WriteLine("\n\n\n\n\n\n\n\n\n\n\n");
                    Console.Write(new string(' ', (Console.WindowWidth - gameover.Length) / 2));
                    Console.WriteLine(gameover);
                    if (userPoints < 0)
                    {
                        userPoints = 0;
                    }
                    userPoints = Math.Max(userPoints, 0);
                    SaveScore(userName, userPoints);
                    string finalPoints = "Your points are: {0}";
                    Console.Write(new string(' ', (Console.WindowWidth - finalPoints.Length) / 2));
                    Console.WriteLine(finalPoints, userPoints);
                    Console.ReadLine();
                    return;
                }

                // 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
                    do
                    {
                        //Generates a new food at a random postion, that is not in the location of the snake'sbody or the obstacles.
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    //Resets the timer
                    lastFoodTime = Environment.TickCount;
                    //Sets the cursor position to the food's row and column
                    Console.SetCursorPosition(food.col, food.row);
                    //Sets the color of the food
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    //Writes an @ in the console which serves as food
                    Console.Write("@");
                    sleepTime--;

                    //Creates a new Position named obstacle
                    Position obstacle = new Position();
                    do
                    {
                        //When the snake collides with the food, it sets obstacle to a new random position that does not contain the snake, the obstacle or food
                        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));

                    //Adds the obstacle into an array of obstacles
                    obstacles.Add(obstacle);
                    //Sets the cursor position the the obstacles column and row
                    Console.SetCursorPosition(obstacle.col, obstacle.row);
                    //Sets the color of the obstacle
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    //Writes = in the console as visualisation of the obstacle
                    Console.Write("=");
                }
                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(" ");
                    do
                    {
                        //Creates a new food at another random postition that does not contain the snake's body or obstacles
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    //Resets the timer
                    lastFoodTime = Environment.TickCount;
                }

                //Sets the cursor position to the new column and row with the food
                Console.SetCursorPosition(food.col, food.row);
                //Change the color to yellow
                Console.ForegroundColor = ConsoleColor.Yellow;
                //Writes an @ to represent food
                Console.Write("@");

                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            first :      byte right = 5, left = 4, down = 4, up = 3 + rax.getnewinfo(a, b, c);
            int lastFoodTime      = 0;
            int foodDissapearTime = 8000;
            int negativePoints    = 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
            };
            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("=");
            }
second:
            Queue <Position> snakeElements = new Queue <Position>();

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

            Position food;

            do
            {
                food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                    randomNumbersGenerator.Next(0, Console.WindowWidth));
            }while (snakeElements.Contains(food) || obstacles.Contains(food));
            Console.SetCursorPosition(food.col, food.row);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("@");

            third :      foreach (Position position in snakeElements)
            {
                Console.SetCursorPosition(position.col, position.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");
            }

            while (true)
            {
                negativePoints++;
                break;
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo userInput = Console.ReadKey();
                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        break;
                        if (direction != right)
                        {
                            direction = left;
                        }
                    }
                    if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        if (direction != left)
                        {
                            direction = right;
                        }
                    }
                    if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        continue;
                        if (direction != down)
                        {
                            direction = up;
                        }
                        continue;
                    }
                    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.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))
                {
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Game over!");
                    int userPoints = (snakeElements.Count - 6) * 100 - negativePoints;
                    //if (userPoints < 0) userPoints = 0;
                    userPoints = Math.Max(userPoints, 0);
                    Console.WriteLine("Your points are: {0}", userPoints);
                    return;
                }

                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 && 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);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("@");
                    sleepTime--;

                    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);
                    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(" ");
                }

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

                Console.SetCursorPosition(food.col, food.row);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("@");

                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 17
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();

            System.Media.SoundPlayer move         = new System.Media.SoundPlayer(@"D:\GitHub\Snake2.0\Snake\sound\move.wav");
            System.Media.SoundPlayer eat          = new System.Media.SoundPlayer(@"D:\GitHub\Snake2.0\Snake\sound\eat.wav");
            System.Media.SoundPlayer gameover     = new System.Media.SoundPlayer(@"D:\GitHub\Snake2.0\Snake\sound\gameover.wav");
            System.Media.SoundPlayer crash        = new System.Media.SoundPlayer(@"D:\GitHub\Snake2.0\Snake\sound\crash.wav");
            System.Media.SoundPlayer powerupsound = new System.Media.SoundPlayer(@"D:\GitHub\Snake2.0\Snake\sound\powerup.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("=");
            }

            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)); //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.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))
                {
                    lives += 1;
                    powerupsound.Play();


                    //Position powerup = new Position(); // randomize the position of the obstacles
                    //do
                    //{
                    //    powerup = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                    //        randomNumbersGenerator.Next(0, Console.WindowWidth));
                    //}
                    //while (snakeElements.Contains(powerup) ||
                    //    powerups.Contains(powerup) ||
                    //    (food.x != powerup.x && food.y != powerup.y));
                    //powerups.Add(powerup);
                    //Console.SetCursorPosition(powerup.y, powerup.x);
                    //Console.ForegroundColor = ConsoleColor.Green;
                    //Console.Write("+");
                }


                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));
                    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.º 18
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      = 10;
            int  _scorecount       = 0;

            if (File.Exists("winner.txt") == true)
            {
                string previouswinner = File.ReadAllText("winner.txt");
                Scoreboard.WriteAt("Previous Winner: " + previouswinner, 0, 0);
            }
            else
            {
                File.Create("winner.txt");
            }
            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 >= 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))
                {
                    //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("Please write your name");
                        string winner = Console.ReadLine();
                        Console.WriteLine("Winner Saved!");
                        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);
            }
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            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

            //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
            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

            //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(0, 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));    //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("=");
            }

            //position of the food
            Position food;

            //randomize the position of the food
            do
            {
                food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                    randomNumbersGenerator.Next(0, Console.WindowWidth));
            }
            //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("@");

            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();
                    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 - 1;                                      //if the snake head hit the left wall, the snake will pass through it and appear on the right wall
                }
                if (snakeNewHead.row < 0)
                {
                    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 = 0;                                                          //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)
                {
                    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 - 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(3, '0'));        //Display the text

                //winning requirement
                if (current_score >= win_score)
                {
                    win_player.Play();
                    //if (userPoints < 0) userPoints = 0;
                    string msg       = "You Win!";
                    string score_msg = "Your points are: " + current_score;
                    string exit_msg  = "Press enter to exit the game.";
                    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 - score_msg.Length) / 2, (Console.WindowHeight / 2) + 1);
                    Console.Write(score_msg);                                                                      //Display the score
                    Console.SetCursorPosition((Console.WindowWidth - exit_msg.Length) / 2, (Console.WindowHeight / 2) + 2);
                    Console.Write(exit_msg);
                    string fullPath = Directory.GetCurrentDirectory() + "/score.txt";
                    using (StreamWriter writer = new StreamWriter(fullPath))
                    {
                        writer.WriteLine(current_score.ToString());
                    }
                    // Read a file

                    string readText = File.ReadAllText(fullPath);
                    Console.ReadLine();
                    return;
                }

                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))                //if the head of the snake hit the body of snake or obstacle
                {
                    gameover_player.Play();
                    string msg       = "Game over!";
                    string score_msg = "Your points are: " + current_score;
                    string exit_msg  = "Press enter to exit the game.";
                    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 - score_msg.Length) / 2, (Console.WindowHeight / 2) + 1);
                    Console.Write(score_msg);                                                                      //Display the score
                    Console.SetCursorPosition((Console.WindowWidth - exit_msg.Length) / 2, (Console.WindowHeight / 2) + 2);
                    Console.Write(exit_msg);
                    string fullPath = Directory.GetCurrentDirectory() + "/score.txt";
                    using (StreamWriter writer = new StreamWriter(fullPath))
                    {
                        writer.WriteLine(current_score.ToString());
                    }
                    // Read a file

                    string readText = File.ReadAllText(fullPath);
                    Console.ReadLine();
                    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 == food.col && snakeNewHead.row == food.row)
                {
                    eat_player.Play();
                    Thread.Sleep(1000);
                    back_player.PlayLooping();
                    // feeding the snake
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));               //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("@");                            //set the shape of food
                    sleepTime--;

                    Position obstacle = new Position();                    //Define a obstacle	position
                    do
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                                randomNumbersGenerator.Next(0, Console.WindowWidth));        //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("=");                                              //write the obstacle to the screen
                }
                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(0, Console.WindowHeight), //randomize the window height of the food position
                                            randomNumbersGenerator.Next(0, Console.WindowWidth)); //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
                }

                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("@");

                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.º 20
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            //JASMINNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
            Console.WriteLine("WELCOME TO SNAKE GAME!");
            Console.WriteLine("Press Enter Key to Continue!");
            Console.Read();

            List <string> menuItems = new List <string>()
            {
                "Start Game",
                "Help",
                "Exit"
            };

            Console.CursorVisible = false;
            while (true)
            {
                string selectedMenuItem = drawMenu(menuItems);
                if (selectedMenuItem == "Start Game")
                {
                    Console.Clear();
                    Console.WriteLine("HELLO!"); Console.Read();
                    //JASMINNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

                    //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;
                    //----------------------------------------Life-----------------------------------
                    int life = 3;
                    //--------------------------------------level------------------------------------
                    int level = 1;


                    int supriseFoodDissapearTime = 3390;
                    int negativePoints           = 0;
                    int winningscore             = 3;
                    int _scorecount = 0;

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

                    if (File.Exists("winner.txt") == true)
                    {
                        string   previouswinner = File.ReadAllText("winner.txt");
                        string[] splitBySpace   = previouswinner.Split(' ');
                        string   first          = splitBySpace.ElementAt(0);
                        int      last           = Convert.ToInt32(splitBySpace.ElementAt(splitBySpace.Length - 1));
                        Scoreboard.WriteAt("Previous Winner: " + previouswinner, 0, 0);

                        if (first == winner)
                        {
                            _scorecount = last;
                        }

                        if (last >= 3)
                        {
                            winningscore = 10;
                        }
                        else if (last >= 10)
                        {
                            winningscore = 30;
                        }
                        else if (last >= 30)
                        {
                            winningscore = 100;
                        }
                    }
                    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);
                    Scoreboard.WriteAt("Your Remains Life", 0, 3);
                    Scoreboard.WriteAt(life.ToString(), 0, 4);
                    Scoreboard.WriteAt("Your Level", 0, 5);
                    Scoreboard.WriteAt(level.ToString(), 0, 6);


                    //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(6, Console.WindowHeight),
                                     randomNumbersGenerator.Next(0, Console.WindowWidth)),
                        new Position(randomNumbersGenerator.Next(6, Console.WindowHeight),
                                     randomNumbersGenerator.Next(0, Console.WindowWidth)),
                        new Position(randomNumbersGenerator.Next(6, Console.WindowHeight),
                                     randomNumbersGenerator.Next(0, Console.WindowWidth)),
                        new Position(randomNumbersGenerator.Next(6, 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("\u2593");
                        //JASMINNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
                    }

                    //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(7, i));
                    }

                    //The position is create randomly
                    //creating food in the game
                    Position food = new Position();
                    food         = CreateFood(food, randomNumbersGenerator, snakeElements, obstacles);
                    lastFoodTime = Environment.TickCount;


                    //The position is create randomly
                    //creating suprising food in the game
                    Position supriseFood = new Position();
                    supriseFood  = CreateSupriseFood(supriseFood, 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("*");
                    }

                    if ((level == 1 && _scorecount >= 3 && _scorecount < 5) || (level == 2 && _scorecount >= 6 && _scorecount < 8) || (level == 3 && _scorecount >= 9 && _scorecount < 10))
                    {
                        level += 1;
                        Scoreboard.WriteAt("Your Level", 0, 5);
                        Scoreboard.WriteAt(level.ToString(), 0, 6);
                        directions[0].col += 1;
                        directions[1].col -= 1;
                        directions[2].row += 1;
                        directions[3].row -= 1;
                    }

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

                            //Only arrow key can display
                            if (userInput.Key != ConsoleKey.LeftArrow || userInput.Key != ConsoleKey.RightArrow || userInput.Key != ConsoleKey.UpArrow || userInput.Key != ConsoleKey.DownArrow)
                            {
                                Console.Clear();
                                Console.ForegroundColor = ConsoleColor.White;

                                if (File.Exists("winner.txt") == true)
                                {
                                    string previouswinner = File.ReadAllText("winner.txt");
                                    Scoreboard.WriteAt("Previous Winner: " + previouswinner, 0, 0);
                                }

                                Scoreboard.WriteAt("Your Current Score", 0, 1);
                                Scoreboard.WriteScore(_scorecount, 0, 2);
                                Scoreboard.WriteAt("Your Remains Life", 0, 3);
                                Scoreboard.WriteAt(life.ToString(), 0, 4);
                                Scoreboard.WriteAt("Your Level", 0, 5);
                                Scoreboard.WriteAt(level.ToString(), 0, 6);

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

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

                                Console.ForegroundColor = ConsoleColor.Yellow;
                                Console.SetCursorPosition(food.col, food.row);
                                Console.Write("♥♥");

                                Console.ForegroundColor = ConsoleColor.Magenta;
                                Console.SetCursorPosition(supriseFood.col, supriseFood.row);
                                Console.Write("?");
                            }
                        }

                        //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);

                        //Game over when snake hits the console window
                        //the game will over if the snake eat its body OR eat the obstacles
                        //Stack which is a linear data structure is used
                        if (snakeNewHead.row < 6 && snakeNewHead.col < 40)
                        {
                            snakeNewHead.col = 0;
                            snakeNewHead.row = 7;
                            direction        = right;
                        }

                        if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead) ||
                            (snakeNewHead.row >= Console.WindowHeight) || (snakeNewHead.col >= Console.WindowWidth) ||
                            (snakeNewHead.col < 0) || (snakeNewHead.row < 0) || collisionObstacle(level, obstacles, snakeNewHead) == true)
                        {
                            //Remove the obstacles which the snake has eaten
                            obstacles.Remove(snakeNewHead);

                            //Game over sound will display if the snake die
                            SoundPlayer player1 = new SoundPlayer();
                            player1.SoundLocation = AppDomain.CurrentDomain.BaseDirectory + "/die.wav";
                            player1.PlaySync();
                            direction        = right;
                            snakeNewHead.row = 7;
                            snakeNewHead.col = 0;

                            //----------------------------------------life---------------------------------------
                            //If user still have life
                            if (life > 0)
                            {
                                //minus 1 life
                                life -= 1;
                                Scoreboard.WriteAt(life.ToString(), 0, 4);

                                //minus 1 score
                                if (_scorecount != 0)
                                {
                                    _scorecount -= 1;
                                    Scoreboard.WriteScore(_scorecount, 0, 2);
                                }

                                Position obstacle = new Position();
                                //generate new position for the obstacles
                                obstacle = CreateObstacle(food, obstacle, randomNumbersGenerator, snakeElements, obstacles);

                                if (player1.IsLoadCompleted == true)
                                {
                                    player.Play();
                                }
                            }
                            //displayed when game over
                            //------------------------------------------------GameOver----------------------------------------------------
                            else
                            {
                                File.WriteAllText("winner.txt", winner + " with score " + _scorecount);
                                Console.Clear();
                                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
                        //JASMINNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
                        if ((collisionFood(level, snakeNewHead, food) == true) || (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("    ");
                            }

                            Console.SetCursorPosition(food.col, food.row); //the cursor position will set to the food position.
                            Console.Write(" ");

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

                            //----------------------------------------level---------------------------------------
                            if ((level == 1 && _scorecount >= 3 && _scorecount < 5) || (level == 2 && _scorecount >= 6 && _scorecount < 8) || (level == 3 && _scorecount >= 9 && _scorecount < 10))
                            {
                                level += 1;
                                Scoreboard.WriteAt("Your Level", 0, 5);
                                Scoreboard.WriteAt(level.ToString(), 0, 6);
                                directions[0].col += 1;
                                directions[1].col -= 1;
                                directions[2].row += 1;
                                directions[3].row -= 1;
                            }

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


                        //when the snake eat the suprise food
                        else if (collisionFood(level, snakeNewHead, supriseFood) == true)
                        {
                            Console.SetCursorPosition(supriseFood.col, supriseFood.row); //the cursor position will set to the food position.
                            Console.Write(" ");

                            _scorecount += 2;
                            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);
                            }
                            //----------------------------------------level---------------------------------------
                            if ((level == 1 && _scorecount >= 3 && _scorecount < 5) || (level == 2 && _scorecount >= 6 && _scorecount < 8) || (level == 3 && _scorecount >= 9 && _scorecount < 10))
                            {
                                level += 1;
                                Scoreboard.WriteAt("Your Level", 0, 5);
                                Scoreboard.WriteAt(level.ToString(), 0, 6);
                                directions[0].col += 1;
                                directions[1].col -= 1;
                                directions[2].row += 1;
                                directions[3].row -= 1;
                            }


                            Position obstacle = new Position();
                            //generate new position for the obstacles
                            obstacle = CreateObstacle(supriseFood, 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
                        }

                        else if (Environment.TickCount - lastFoodTime >= supriseFoodDissapearTime)
                        {
                            negativePoints = negativePoints + 50;
                            Console.SetCursorPosition(supriseFood.col, supriseFood.row); //the cursor position will set to the food position.
                            Console.Write(" ");
                            supriseFood  = CreateSupriseFood(supriseFood, randomNumbersGenerator, snakeElements, obstacles);
                            lastFoodTime = Environment.TickCount; //The lastFoodTime will reset to the present time
                        }

                        sleepTime -= 0.01;

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

                else if (selectedMenuItem == "Help")
                {
                    Console.WriteLine("WELCOME TO SNAKE GAME!");
                    Console.WriteLine("Keyboard Up = Up");
                    Console.WriteLine("Keyboard Down = Down");
                    Console.WriteLine("Keyboard Right = Right");
                    Console.WriteLine("Keyboard Left = Left");
                    Console.WriteLine("Press Enter Key to Continue!");
                    Console.Read();
                }

                else if (selectedMenuItem == "Exit")
                {
                    Environment.Exit(0);
                }
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Main starts here
        /// </summary>
        //Define direction by using index number
        //Set the time taken for the food to be dissappear
        //Initialise negative points
        static void Main(string[] args)
        {
            byte right             = 0;
            byte left              = 1;
            byte down              = 2;
            byte up                = 3;
            int  currentTime       = Environment.TickCount;
            int  lastFoodTime      = 0;
            int  foodDissapearTime = 10000; //food dissappears after 10 second
            int  negativePoints    = 0;
            int  userPoints        = 0;

            Position[] directions = new Position[4];

            Console.SetWindowSize(56, 38);
            Program p = new Program();

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

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

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

            p.InitialRandomObstacles(obstacles);

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

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

            //Initialise the snake position in top left corner of the windows
            //Havent draw the snake elements in the windows yet. Will be drawn in the code below
            Queue <Position> snakeElements = new Queue <Position>();

            for (int i = 0; i <= 3; i++) // Length of the snake was reduced to 3 units of *
            {
                snakeElements.Enqueue(new Position(1, i));
            }

            //To position food randomly when the program runs first time
            Position food = new Position();

            p.GenerateFood(ref food, snakeElements, obstacles);

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

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

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

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

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

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

                p.PrintUserPoint(userPoints, snakeElements, negativePoints);

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

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

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

                //Snake head shape when the user presses the key to change his direction
                snakeElements.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                Console.ForegroundColor = ConsoleColor.Gray;
                if (direction == right)
                {
                    Console.Write(">");                     //Snake head when going right
                }
                if (direction == left)
                {
                    Console.Write("<");                   //Snake head when going left
                }
                if (direction == up)
                {
                    Console.Write("^");                 //Snake head when going up
                }
                if (direction == down)
                {
                    Console.Write("v");                   //Snake head when going down
                }
                // food will be positioned randomly until they are not at the same row & column as snake head
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                {
                    Console.Beep();// Make a sound effect when food was eaten.
                    p.GenerateFood(ref food, snakeElements, obstacles);


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

                    //Generate new obstacle
                    p.GenerateNewObstacle(ref food, snakeElements, obstacles);
                }
                else
                {
                    // snake is moving
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(" ");
                }

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

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

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

                //snake moving speed increased
                sleepTime -= 0.01;

                //pause the execution thread of snake moving speed
                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 22
0
        static void Main()
        {
            byte   right             = 0;
            byte   left              = 1;
            byte   down              = 2;
            byte   up                = 3;
            int    lastFoodTime      = 0;
            int    foodDissapearTime = 8000;
            double negativePoints    = 0;
            int    userPoints        = 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
            };
            double sleepTime = 100;
            int    direction = right;

            Console.BufferHeight = Console.WindowHeight;
            Random randomNumberGenerator = new Random();

            Console.CursorVisible = false;

            // create new snake
            Queue <Position> snakeElements = new Queue <Position>();

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

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


            List <Position> obstacles = new List <Position>()
            {
                new Position(12, 12),
                new Position(14, 20),
                new Position(7, 7)
            };

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

            // create new food
            Position food;

            do
            {
                //create new food
                food = new Position(randomNumberGenerator.Next(0, Console.WindowHeight),
                                    randomNumberGenerator.Next(0, Console.WindowWidth));
            }while (snakeElements.Contains(food) || obstacles.Contains(food));
            lastFoodTime = Environment.TickCount;

            Console.SetCursorPosition(food.col, food.row);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("@");


            while (true)
            {
                negativePoints += 0.1;
                // Getting user input
                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 nextDirection = directions[direction];
                Position snakeHead     = snakeElements.Last();
                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.col >= Console.WindowWidth)
                {
                    snakeNewHead.col = 0;
                }
                if (snakeNewHead.row >= Console.WindowHeight)
                {
                    snakeNewHead.row = 0;
                }

                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                {
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Game Over!");
                    userPoints = (snakeElements.Count - 6) * 100 - (int)negativePoints;
                    userPoints = Math.Max(userPoints, 0);
                    Console.WriteLine("Your points are: {0}", userPoints);
                    return;
                }

                // moving, adding snake new head
                Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("*");
                snakeElements.Enqueue(snakeNewHead);
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                Console.ForegroundColor = ConsoleColor.Green;
                if (direction == right)
                {
                    Console.Write(">");
                }
                if (direction == left)
                {
                    Console.Write("<");
                }
                if (direction == up)
                {
                    Console.Write("^");
                }
                if (direction == down)
                {
                    Console.Write("v");
                }

                // snake next move food detection
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                {
                    // feeding, not removing the last snake element
                    do
                    {
                        //create new food
                        food = new Position(randomNumberGenerator.Next(0, Console.WindowHeight),
                                            randomNumberGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    lastFoodTime = Environment.TickCount;

                    Console.SetCursorPosition(food.col, food.row);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("@");
                    sleepTime--;

                    Position obstacle;
                    do
                    {
                        //create new obsticle
                        obstacle = new Position(randomNumberGenerator.Next(0, Console.WindowHeight),
                                                randomNumberGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(obstacle) || obstacles.Contains(obstacle) ||
                            food.row == obstacle.row || food.col == obstacle.col);
                    obstacles.Add(obstacle);
                    Console.SetCursorPosition(obstacle.col, obstacle.row);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("!");
                }
                else
                {
                    // not feeding, removing last snake element
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    Console.Write(" ");
                }

                // check food expiration
                if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                {
                    negativePoints += 50;
                    // remove old food
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write(" ");

                    do
                    {
                        //create new food
                        food = new Position(randomNumberGenerator.Next(0, Console.WindowHeight),
                                            randomNumberGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    lastFoodTime = Environment.TickCount;

                    Console.SetCursorPosition(food.col, food.row);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("@");
                }

                Console.SetCursorPosition((Console.WindowWidth / 2) - 5, 0);
                Console.ForegroundColor = ConsoleColor.Red;
                userPoints = (snakeElements.Count - 6) * 100 - (int)negativePoints;
                userPoints = Math.Max(userPoints, 0);
                Console.WriteLine("points: {0}", userPoints);

                sleepTime -= 0.01;
                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 23
0
        public static void Main(string[] args)
        {
            // Assigning values to right, left, down, up as index
            byte   right              = 0;
            byte   left               = 1;
            byte   down               = 2;
            byte   up                 = 3;
            int    gLastFoodTime      = 0;
            int    gFoodDissapearTime = 12000; // Time for food to dissapear in milliseconds
            int    gNegativePoints    = 0;     // Points to be deducted from the final score
            string gDifficulty        = "normal";
            double gSleepTime         = 100;   // Velocity of snake
            int    gbonuspoints       = 0;

            while (true)
            {
                Console.BufferHeight = Console.WindowHeight; // Intialize the height of the game window
                Console.BufferWidth  = Console.WindowWidth;  // Initialize the width of the game window
                Console.Clear();
                Draw("White", Console.BufferWidth / 2 - 3, Console.BufferHeight / 2 - 6, "Main Menu");
                Draw("White", Console.BufferWidth / 2 - 8, Console.BufferHeight / 2 - 5, "------------------------");
                Draw("White", Console.BufferWidth / 2 - 8, Console.BufferHeight / 2 - 4, "[1] Start Game");
                Draw("White", Console.BufferWidth / 2 - 8, Console.BufferHeight / 2 - 3, "[2] Difficulty");
                Draw("White", Console.BufferWidth / 2 - 8, Console.BufferHeight / 2 - 2, "[3] Highscores");
                Draw("White", Console.BufferWidth / 2 - 8, Console.BufferHeight / 2 - 1, "[4] Instructions");
                Draw("White", Console.BufferWidth / 2 - 8, Console.BufferHeight / 2, "[5] Exit\n");
                Draw("White", Console.BufferWidth / 2 - 8, Console.BufferHeight / 2 + 2, "Enter Your Selection: ");
                string gSelection = Console.ReadLine();

                if (gSelection == "1")
                {
                    break;
                }

                else if (gSelection == "2")
                {
                    Console.Clear();
                    Draw("White", Console.BufferWidth / 2 - 5, Console.BufferHeight / 2 - 6, "Current Difficulty: " + gDifficulty);
                    Draw("White", Console.BufferWidth / 2 - 5, Console.BufferHeight / 2 - 4, "Select difficulty level");
                    Draw("White", Console.BufferWidth / 2 - 2, Console.BufferHeight / 2 - 3, "[1] Easy");
                    Draw("White", Console.BufferWidth / 2 - 2, Console.BufferHeight / 2 - 2, "[2] Normal");
                    Draw("White", Console.BufferWidth / 2 - 2, Console.BufferHeight / 2 - 1, "[3] Hard\n");
                    Draw("White", Console.BufferWidth / 2 - 5, Console.BufferHeight / 2 + 1, "Enter Your Selection: ");

                    // Sets value of difficulty
                    gDifficulty = Console.ReadLine();
                }

                else if (gSelection == "3")
                {
                    Console.Clear(); //To clear out current screen
                    // Display Scoreboard
                    string[] content = File.ReadAllLines(@"..\Scores\score.txt");
                    Console.WriteLine("Scoreboard");
                    foreach (string x in content)
                    {
                        Console.WriteLine(x);
                    }

                    Console.WriteLine("\nPress enter to continue...");
                    Console.ReadLine();
                }

                else if (gSelection == "4")
                {
                    // Implement instructions here..
                    Console.Clear();
                    Console.WriteLine("Instructions:" +
                                      "\n1. Move the snake using arrow keys." +
                                      "\n2. Avoid colliding with the obstacle '='" +
                                      "\n3. Eat the food '@' using the snake head '>' to gain the snake length '*' ");
                    Console.WriteLine("\nPress enter to continue...");
                    Console.ReadLine();
                }

                else
                {
                    System.Environment.Exit(0);
                }
            }
            Console.Clear(); //To clear out current screen

            //Input for player name
            Console.SetCursorPosition(Console.WindowWidth / 2 - 8, 13); //Reposition the string
            Console.WriteLine("Type in your username: "******"_______________________");
            Console.SetCursorPosition(Console.WindowWidth / 2 - 8, 14); //Reposition the string
            string lPlyr_name = Console.ReadLine();

            Console.Clear(); //To clear out current screen
            Draw("Blue", 12, 0, "Player Name:  " + lPlyr_name);

            // Initialize Snake Movement value
            Position[] gDirections = new Position[]
            {
                new Position(0, 1),  // Move right
                new Position(0, -1), // Move left
                new Position(1, 0),  // Move down
                new Position(-1, 0), // Move up
            };

            // Changes speed of snake according to difficulty
            switch (gDifficulty)
            {
            case "1":
                gSleepTime = 150;
                break;

            case "2":
                gSleepTime = 100;
                break;

            case "3":
                gSleepTime = 50;
                break;

            default:
                gSleepTime = 100;
                break;
            }

            int    gDirection = right;                     // Initialize default snake direction
            Random gRandomNumbersGenerator = new Random(); // Random number generator

            gLastFoodTime = Environment.TickCount;         // Get time since program has started

            // Initialize obstacle locations
            List <Position> gObstacles = new List <Position>()
            {
                new Position(gRandomNumbersGenerator.Next(1, Console.WindowHeight), gRandomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(gRandomNumbersGenerator.Next(1, Console.WindowHeight), gRandomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(gRandomNumbersGenerator.Next(1, Console.WindowHeight), gRandomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(gRandomNumbersGenerator.Next(1, Console.WindowHeight), gRandomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(gRandomNumbersGenerator.Next(1, Console.WindowHeight), gRandomNumbersGenerator.Next(0, Console.WindowWidth)),
            };

            // Initialize obstacle color
            foreach (Position obstacle in gObstacles)
            {
                Draw("Cyan", obstacle.col, obstacle.row, "=");
            }

            // Initialize length of snake
            Queue <Position> gSnakeElements = new Queue <Position>();

            for (int i = 0; i <= 3; i++)
            {
                gSnakeElements.Enqueue(new Position(1, i)); // Changed so that starts on second line
            }

            // Initilize random food
            Random        randomfood = new Random();
            List <string> foodtype   = new List <string> {
                "@", "#", "$", "%"
            };
            int index = randomfood.Next(foodtype.Count);

            // Initialize food
            Position gFood;

            do
            {
                gFood = new Position(gRandomNumbersGenerator.Next(1, Console.WindowHeight),
                                     gRandomNumbersGenerator.Next(0, Console.WindowWidth)); // Initialize coordinate of food (random)
            }while (gSnakeElements.Contains(gFood) || gObstacles.Contains(gFood));          // To detect whether the food collides with the obstacles/snake body
            Draw("Yellow", gFood.col, gFood.row, foodtype[index]);

            // Initialize snake body
            foreach (Position position in gSnakeElements)
            {
                Draw("DarkGray", position.col, position.row, "*");
            }

            // Initialize soundplayer
            SoundPlayer player = new SoundPlayer();

            player.SoundLocation = @"..\Sounds\bgm.wav";
            player.Play();


            // Main game loop
            while (true)
            {
                // Initialize negative points (deducted from total score)
                gNegativePoints++;

                // Initialize scoreboard
                int userPoints = (gSnakeElements.Count - 4) * 100 + gbonuspoints - gNegativePoints;
                if (userPoints < 0)
                {
                    userPoints = 0;
                }
                userPoints = Math.Max(userPoints, 0);

                Draw("Green", 0, 0, "Score: " + userPoints);

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

                    // Prevents snake from going backwards
                    if (userInput.Key == ConsoleKey.LeftArrow)
                    {
                        if (gDirection != right)
                        {
                            gDirection = left;
                        }
                    }
                    if (userInput.Key == ConsoleKey.RightArrow)
                    {
                        if (gDirection != left)
                        {
                            gDirection = right;
                        }
                    }
                    if (userInput.Key == ConsoleKey.UpArrow)
                    {
                        if (gDirection != down)
                        {
                            gDirection = up;
                        }
                    }
                    if (userInput.Key == ConsoleKey.DownArrow)
                    {
                        if (gDirection != up)
                        {
                            gDirection = down;
                        }
                    }
                }

                Position gSnakeHead     = gSnakeElements.Last();   // Returns last element in the queue, assigns the element as coordinate of snakeHead
                Position gNextDirection = gDirections[gDirection]; // The direction will be converted to integer as index, nextDirection will store the difference of the next coordinate

                Position gSnakeNewHead = new Position(gSnakeHead.row + gNextDirection.row,
                                                      gSnakeHead.col + gNextDirection.col); // Adds to the next position of the snake head

                // Makes sure that the snake doesn't go out of bounds
                if (gSnakeNewHead.col < 0)
                {
                    gSnakeNewHead.col = Console.WindowWidth - 1;
                }
                if (gSnakeNewHead.row < 1)
                {
                    gSnakeNewHead.row = Console.WindowHeight - 1;
                }
                if (gSnakeNewHead.row >= Console.WindowHeight)
                {
                    gSnakeNewHead.row = 1;
                }
                if (gSnakeNewHead.col >= Console.WindowWidth)
                {
                    gSnakeNewHead.col = 0;
                }

                // If the snake is size 15, the player wins and the game ends
                if (gSnakeElements.Count == 15)
                {
                    Draw("Green", 0, 0, "");
                    Console.SetCursorPosition(Console.WindowWidth / 2, 10);     //Reposition the string
                    Console.WriteLine("You won!");
                    Console.SetCursorPosition(Console.WindowWidth / 2 - 4, 11); //Reposition the string
                    Console.WriteLine("Your points are: {0}", userPoints);
                    Console.SetCursorPosition(Console.WindowWidth / 2 - 8, 13); //Reposition the string
                    string lScore = "Score: " + userPoints.ToString();
                    System.IO.File.WriteAllText(@"..\Scores\score.txt", lScore);
                    Console.WriteLine("Press Enter to exit the game");
                    Console.ReadLine();
                    return;
                }

                // If the snake head collides with the snake body or the snake head hits an obstacle, the game loop ends
                if (gSnakeElements.Contains(gSnakeNewHead) || gObstacles.Contains(gSnakeNewHead))
                {
                    Draw("Red", 0, 0, "");
                    Console.SetCursorPosition(Console.WindowWidth / 2, 10);     //Reposition the string
                    Console.WriteLine("Game over!");
                    Console.SetCursorPosition(Console.WindowWidth / 2 - 4, 11); //Reposition the string
                    Console.WriteLine("Your points are: {0}", userPoints);
                    Console.SetCursorPosition(Console.WindowWidth / 2 - 8, 13); //Reposition the string
                    string lScore = "Score: " + userPoints.ToString();

                    //Updating score text file
                    using (StreamWriter lFile = File.AppendText(@"..\Scores\score.txt"))
                    {
                        lFile.WriteLine("\nPlayer : " + lPlyr_name);
                        lFile.WriteLine(lScore);
                        lFile.WriteLine("--------------------");
                    }
                    Console.WriteLine("Press Enter to exit the game");
                    Console.ReadLine();
                    return;
                }

                Draw("DarkGray", gSnakeHead.col, gSnakeHead.row, "*");

                gSnakeElements.Enqueue(gSnakeNewHead);
                Console.SetCursorPosition(gSnakeNewHead.col, gSnakeNewHead.row);
                Console.ForegroundColor = ConsoleColor.Gray;
                if (gDirection == right)
                {
                    Console.Write(">");
                }
                else if (gDirection == left)
                {
                    Console.Write("<");
                }
                else if (gDirection == up)
                {
                    Console.Write("^");
                }
                else
                {
                    Console.Write("v");
                }

                // feeding the snake
                if (gSnakeNewHead.col == gFood.col && gSnakeNewHead.row == gFood.row)
                {
                    if (foodtype[index] == "@")
                    {
                        gbonuspoints += 100;
                    }
                    else if (foodtype[index] == "#")
                    {
                        gbonuspoints += 150;
                    }
                    else if (foodtype[index] == "$")
                    {
                        gbonuspoints += 200;
                    }
                    else if (foodtype[index] == "%")
                    {
                        gbonuspoints += 250;
                    }
                    else
                    {
                        gbonuspoints += 0;
                    }

                    do
                    {
                        // Randomize food
                        index = randomfood.Next(foodtype.Count);
                        gFood = new Position(gRandomNumbersGenerator.Next(1, Console.WindowHeight),
                                             gRandomNumbersGenerator.Next(0, Console.WindowWidth)); // Assign two random values into food position
                    }while (gSnakeElements.Contains(gFood) || gObstacles.Contains(gFood));          // To detect whether the snake/obstacle collides with food

                    gLastFoodTime = Environment.TickCount;                                          //
                    Draw("Yellow", gFood.col, gFood.row, foodtype[index]);
                    gSleepTime--;                                                                   // Increase the velocity that the snake is travelling

                    Position obstacle = new Position();                                             // Initialize position of obstacle

                    do
                    {
                        obstacle = new Position(gRandomNumbersGenerator.Next(1, Console.WindowHeight),
                                                gRandomNumbersGenerator.Next(0, Console.WindowWidth)); // Assign to random values into obstacle position
                    }while (gSnakeElements.Contains(obstacle) ||
                            gObstacles.Contains(obstacle) ||
                            (gFood.row != obstacle.row && gFood.col != obstacle.row)); // Makes sure the obstacles do not spawn inside the food or other obstacles
                    gObstacles.Add(obstacle);                                          // Adds a new obstacle to the queue
                    Draw("Cyan", obstacle.col, obstacle.row, "=");                     // Draws obstacle
                }
                else
                {
                    // moving...
                    Position last = gSnakeElements.Dequeue();      // Deletes the last element of the list
                    Console.SetCursorPosition(last.col, last.row); // Moves cursor to the position of deleted element
                    Console.Write(" ");                            // Replaces the space in the position with space
                }

                if (Environment.TickCount - gLastFoodTime >= gFoodDissapearTime) // Food destructor
                {
                    gNegativePoints = gNegativePoints + 50;                      // Deduct points for not eating food
                    Console.SetCursorPosition(gFood.col, gFood.row);             // Moves cursor to the food about to be deleted
                    Console.Write(" ");                                          // Deletes the food drawn at that position
                    do
                    {
                        // Randomize food
                        index = randomfood.Next(foodtype.Count);
                        gFood = new Position(gRandomNumbersGenerator.Next(0, Console.WindowHeight),
                                             gRandomNumbersGenerator.Next(0, Console.WindowWidth)); // Assigns new position to the food
                    }while (gSnakeElements.Contains(gFood) || gObstacles.Contains(gFood));          // Loops for a new position for food until a valid position is set and drawn
                    gLastFoodTime = Environment.TickCount;                                          //
                }

                // Draws food
                Draw("Yellow", gFood.col, gFood.row, foodtype[index]);

                gSleepTime -= 0.01; // Increase the velocity of the snake each time the loop is run

                Thread.Sleep((int)gSleepTime);
            }
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            bool restart   = true;
            bool menu      = true;
            bool gameStart = false;

            if (menu)
            {
                ConsoleKeyInfo userInput = mainMenu();
                while (true)
                {
                    if (userInput.Key == ConsoleKey.Enter)
                    {
                        menu      = false;
                        gameStart = true;
                        Console.Clear();
                    }
                    if (userInput.Key == ConsoleKey.Spacebar)
                    {
                        menu      = false;
                        gameStart = true;
                        Main(null);
                        Console.ReadLine();
                    }

                    if (userInput.Key == ConsoleKey.Escape)
                    {
                        Console.Clear();
                        Environment.Exit(0);
                    }
                    break;
                }
            }
            while (restart)
            {
                restart = false;
                if (gameStart)
                {
                    Console.Clear();
                    //adds background music to game
                    musicMedia();

                    //Initializing variables
                    bool superFood         = false;
                    byte right             = 0;
                    byte left              = 1;
                    byte down              = 2;
                    byte up                = 3;
                    int  lastFoodTime      = 0;
                    int  foodDissapearTime = 15000;
                    int  negativePoints    = 0;
                    int  checkPoint        = 300;

                    //A array of Position entities called directions
                    //defining the direction that the snake can move
                    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;
                    lastFoodTime         = Environment.TickCount;

                    //A list of Positions entity that contain the positions of the obstacle
                    List <Position> obstacles = new List <Position>();

                    for (int i = 0; i < 5; i++)
                    {
                        obstacles.Add(new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                                   randomNumbersGenerator.Next(0, Console.WindowWidth)));
                    }


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

                    //creating the snake and putting the coordinates into queue
                    Queue <Position> snakeElements = new Queue <Position>();
                    for (int i = 0; i <= 3; i++)
                    {
                        snakeElements.Enqueue(new Position(0, i));
                    }

                    //Creating position for the food and displaying it
                    //The loop continues until the food element is not in snakeElements or obstacles
                    Position food;
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    Console.SetCursorPosition(food.col, food.row);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("@");

                    //Displaying the snake
                    foreach (Position position in snakeElements)
                    {
                        drawSnake(position);
                    }
                    Position createObject(Position posObject, ConsoleColor color)
                    {
                        do
                        {
                            posObject = new Position(randomNumbersGenerator.Next(1, Console.WindowHeight),
                                                     randomNumbersGenerator.Next(0, Console.WindowWidth));
                        }while (snakeElements.Contains(posObject) || obstacles.Contains(posObject));
                        Console.SetCursorPosition(posObject.col, posObject.row);
                        Console.ForegroundColor = color;
                        return(posObject);
                    }

                    while (true)
                    {
                        negativePoints++;

                        if (Console.KeyAvailable)
                        {
                            ConsoleKeyInfo userInput = Console.ReadKey();
                            if (userInput.Key == ConsoleKey.LeftArrow)                             //if direction isnt equal to right it will move left
                            {
                                if (direction != right)
                                {
                                    direction = left;
                                }
                            }
                            if (userInput.Key == ConsoleKey.RightArrow)                             //if right arrow click it will move to the right
                            {
                                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;
                                }
                            }


                            if (userInput.Key == ConsoleKey.Spacebar && menu == false)
                            {
                                ConsoleKeyInfo pauseInput = mainMenu();
                                if (pauseInput.Key == ConsoleKey.Spacebar)
                                {
                                    Console.Clear();
                                    foreach (Position obstacle in obstacles)
                                    {
                                        Console.ForegroundColor = ConsoleColor.Cyan;
                                        Console.SetCursorPosition(obstacle.col, obstacle.row);
                                        Console.Write("=");
                                    }
                                }
                                if (pauseInput.Key == ConsoleKey.Enter)
                                {
                                    Console.Clear();
                                    restart = true;
                                    break;
                                }
                                if (pauseInput.Key == ConsoleKey.Escape)
                                {
                                    Console.Clear();
                                    Environment.Exit(0);
                                }
                            }
                        }

                        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 < 1)
                        {
                            snakeNewHead.row = Console.WindowHeight - 1;
                        }
                        if (snakeNewHead.row >= Console.WindowHeight)
                        {
                            snakeNewHead.row = 1;
                        }
                        if (snakeNewHead.col >= Console.WindowWidth)
                        {
                            snakeNewHead.col = 0;
                        }

                        //Displaying the score
                        int userPoints = (snakeElements.Count - 6) * 100 - negativePoints;
                        //if (userPoints < 0) userPoints = 0;
                        Console.SetCursorPosition(0, 0);
                        Console.ForegroundColor = ConsoleColor.White;
                        userPoints = Math.Max(userPoints, 0);
                        //game get harder when user reach certain point
                        if (userPoints > checkPoint)
                        {
                            checkPoint        += 300;
                            sleepTime         -= 20;
                            foodDissapearTime -= 2000;
                            if (foodDissapearTime <= 5000)
                            {
                                foodDissapearTime = 5000;
                            }
                            if (sleepTime <= 20)
                            {
                                sleepTime = 20;
                            }
                        }
                        //if snake overlap with obstacle or snake, game is over
                        if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                        {
                            end("Game Over!", userPoints);
                            return;
                        }

                        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(">");                                             //direction for snake moving right
                        }
                        if (direction == left)
                        {
                            Console.Write("<");                                           //direction for snake moving left and so forth
                        }
                        if (direction == up)
                        {
                            Console.Write("^");
                        }
                        if (direction == down)
                        {
                            Console.Write("v");
                        }
                        //check snakehead overlapping food position
                        if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                        {
                            //create new obstacle position object until no overlapping with snake and other obstacle
                            Position obstacle = new Position();
                            obstacle = createObject(obstacle, ConsoleColor.Cyan);
                            obstacles.Add(obstacle);
                            Console.Write("=");
                            // feeding the snake
                            //create new food position object until position is not overlapping snake or obstacle
                            food = createObject(food, ConsoleColor.Yellow);
                            //more point if super food
                            if (superFood == true)
                            {
                                negativePoints -= 200;
                                superFood       = false;
                            }
                            //refresh last food eat time timer counter
                            lastFoodTime = Environment.TickCount;
                            int randomNumber = randomNumbersGenerator.Next(0, 11);
                            if (randomNumber % 2 == 0)
                            {
                                superFood = true;
                            }
                            sleepTime--;
                        }
                        else
                        {
                            // moving...
                            //move the snake to new postion and delete the last snake element
                            Position last = snakeElements.Dequeue();
                            Console.SetCursorPosition(last.col, last.row);
                            Console.Write(" ");
                        }
                        //when timer counter between eating last food is higher than default food dissapear time
                        if (Environment.TickCount - lastFoodTime >= foodDissapearTime)
                        {
                            //decrease user score by 50 if user take too long to eat the food
                            //delete the food
                            superFood      = false;
                            negativePoints = negativePoints + 50;
                            Console.SetCursorPosition(food.col, food.row);
                            Console.Write(" ");
                            //create new food position until no overlapping with obstacle and snake
                            food = createObject(food, ConsoleColor.Yellow);
                            //refresh last food eat time timer counter
                            lastFoodTime = Environment.TickCount;
                        }

                        //This will clear the previous score shown then display the new score
                        gameScore(userPoints);

                        Console.SetCursorPosition(food.col, food.row);
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        if (superFood == true)
                        {
                            Console.Write("$");
                        }
                        else
                        {
                            Console.Write("@");
                        }
                        sleepTime -= 0.01;

                        Thread.Sleep((int)sleepTime);
                    }
                }
            }
        }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            PlayMusic();
            byte right = 0;
            byte left  = 1;
            byte down  = 2;
            byte up    = 3;
            //means the last time the snakeElement ate
            int lastFoodTime = 0;
            //the time till the food spawns again
            int foodDissapearTime = 30000;
            int userPoints        = 0;
            int negativePoints    = 0;
            int highScore         = 0;

            //array storing the direction of snake movement
            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 number generator
            Random randomNumbersGenerator = new Random();

            //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;
            int randomNumber = 0;

            //create Position objects and stores them in obstacles
            //These represent the obstacles
            List <Position> obstacles = new List <Position>()
            {
                //-1 prevents the obstacle from spawaning on the userpoints display
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight - 1),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight - 1),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight - 1),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight - 1),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
                new Position(randomNumbersGenerator.Next(0, Console.WindowHeight - 1),
                             randomNumbersGenerator.Next(0, Console.WindowWidth)),
            };

            //This draws the obstacles on the screen
            foreach (Position obstacle in obstacles)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.SetCursorPosition(obstacle.col, obstacle.row);
                Console.Write("=");
            }

            //Creates the snake using a queue data structure of length 3
            //Queue operates as a first-in first-out array
            Queue <Position> snakeElements = new Queue <Position>();

            //sets the length of snake equal to 3
            for (int i = 0; i <= 3; i++)
            {
                snakeElements.Enqueue(new Position(0, i));
            }
            //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 = MakeFood(randomNumbersGenerator, snakeElements, obstacles, randomNumber);

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

            //main game loop
            while (true)
            {
                int rng = randomNumbersGenerator.Next(8);
                negativePoints++;
                //checks if user can input values through keyboard
                if (Console.KeyAvailable)
                {
                    //The controls of the snake
                    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;
                        }
                    }
                }
                //return the last element in the snakebody
                Position snakeHead = snakeElements.Last();
                //sets the direction the snake will move
                Position nextDirection = directions[direction];

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

                //allows the snake to exit the window and enter at the opposite side
                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;
                }

                //user points calculation
                userPoints = (snakeElements.Count - 3) * 100 - negativePoints;
                if (userPoints < 0)
                {
                    userPoints = 0;
                }
                //userPoints = Math.Max(userPoints, 0);
                if (userPoints > highScore)
                {
                    highScore = userPoints;
                }
                //displays points while playing game
                string displaypoints = $" Points:{userPoints}";
                Console.SetCursorPosition(Console.WindowWidth - displaypoints.Length, 0);
                Console.WriteLine(displaypoints);
                //checks snake collision with obstacles and ends the game
                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                {
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.SetCursorPosition(55, (Console.WindowHeight - 1) / 2);
                    Console.WriteLine("Game over!");
                    //6 and not 5 because we enqueue snakeNewHead and dont dequeue snakeHead
                    string points = $"Your points are: {userPoints}";
                    Console.SetCursorPosition(50, 15);
                    Console.WriteLine(points);
                    Console.SetCursorPosition(53, 16);
                    Console.WriteLine("High Score: " + highScore);
                    Console.ReadLine();
                    using (StreamWriter sw = File.CreateText("..\\..\\user.txt"))
                    {
                        sw.WriteLine(points);
                    }

                    return;
                }
                //winning game logic
                if (userPoints >= 500)
                {
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Congratulations!!! You Win !!!");
                    string points = $"Your points are: {userPoints}";
                    Console.WriteLine(points);
                    using (StreamWriter sw = File.CreateText("..\\.."))
                    {
                        sw.WriteLine(points);
                    }
                    return;
                }

                //sets the last element in the queue to be *
                Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");

                //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);
                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");
                }

                //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
                    if (rng == 1)
                    {
                        userPoints += 150;
                    }

                    food = MakeFood(randomNumbersGenerator, snakeElements, obstacles, rng);
                    sleepTime--;

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


                    Position obstacle;
                    do
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight - 1),
                                                randomNumbersGenerator.Next(0, Console.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);
                    Console.SetCursorPosition(obstacle.col, obstacle.row);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("=");
                }
                else
                {
                    //dequeue removes the first element added in the queue and returns it
                    //
                    // moving...
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    Console.Write(" ");
                }

                //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 = negativePoints + 10;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.Write(" ");

                    food         = MakeFood(randomNumbersGenerator, snakeElements, obstacles, rng);
                    lastFoodTime = Environment.TickCount;
                }
                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 26
0
        //Main Program
        static void Main(string[] args)
        {
            // Set the Foreground color to blue
            Console.BackgroundColor
                = ConsoleColor.Black;

            // Display current Foreground color
            Console.ForegroundColor
                = ConsoleColor.Gray;

            byte   right             = 0;
            byte   left              = 1;
            byte   down              = 2;
            byte   up                = 3;
            int    lastFoodTime      = 0;
            int    negativePoints    = 0;
            int    foodDissapearTime = 0;
            double sleepTime         = 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;
            }
            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)));
            }
            //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++)
            {
                snakeElements.Enqueue(new Position(0, 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 - 2;
                }
                if (snakeNewHead.row < 0)
                {
                    snakeNewHead.row = Console.WindowHeight - 2;
                }
                if (snakeNewHead.row >= Console.WindowHeight)
                {
                    snakeNewHead.row = 0;
                }
                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.DarkGray;
                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
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                {
                    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);
                    Console.SetCursorPosition(obstacle.col, 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.º 27
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)
            {
                Level levelnow = Level.One;
                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("O");
                    }

                    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 + " ");



                        levelnow = WinCondition(userName, userPoints, levelnow);

                        // 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 < 5)
                        {
                            snakeNewHead.col = Console.WindowWidth - 6;
                        }
                        if (snakeNewHead.row < 5)
                        {
                            snakeNewHead.row = Console.WindowHeight - 6;
                        }
                        if (snakeNewHead.row >= Console.WindowHeight - 5)
                        {
                            snakeNewHead.row = 5;
                        }
                        if (snakeNewHead.col >= Console.WindowWidth - 5)
                        {
                            snakeNewHead.col = 5;
                        }

                        //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)
                            {
                                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("O");

                        // 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.col == food.col + 1) && snakeNewHead.row == food.row)
                        {
                            Console.Beep();
                            Console.SetCursorPosition(food.col, food.row);
                            Console.Write(" ");
                            Console.SetCursorPosition(food.col + 1, food.row);
                            Console.Write(" ");
                            //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(" ");
                            Console.SetCursorPosition(food.col + 1, 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 (levelnow == Level.End)
                        {
                            mainloop = false;
                            state    = GameState.InMainMenu;
                        }
                    }
                }
                else if (state == GameState.InMainMenu)
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("\n <OOO 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 ( OOO> ).");
                    Console.WriteLine(" ");
                    Console.WriteLine("Your goal is to eat the food ( \u2665\u2665 ) 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.º 28
0
        //the main compiler
        static void Main(string[] args)
        {
            byte right             = 0;
            byte left              = 1;
            byte down              = 2;
            byte up                = 3;
            int  lastFoodTime      = 0;
            int  foodDissapearTime = 8000;
            int  negativePoints    = 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
            };

            double sleepTime = 100;

            int    direction = right; //this defaults the snake's direction to right when the game starts
            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
                new Position(12, 12),
                new Position(14, 20),
                new Position(7, 7),
                new Position(19, 19),
                new Position(6, 9),
            };

            // For loop for creating the obstacles
            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));
            }

            //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));
            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("*");
            }//the body of the snake

            while (true)
            {
                negativePoints++;
                //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);

                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;
                }
                //when the snake collides with a wall, it will in turn appear at the opposite side of the wall

                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                {
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Game over!");
                    int userPoints = (snakeElements.Count - 6) * 100 - negativePoints;
                    //if (userPoints < 0) userPoints = 0;
                    userPoints = Math.Max(userPoints, 0);
                    Console.WriteLine("Your points are: {0}", userPoints);
                    return;
                }
                //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

                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");
                }
                //whenever the snake changes direction, the head of the snake changes according to the direction

                // feeding the snake
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row) //if snake head's coordinates is same with food
                {
                    //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;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("@");
                    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);
                    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(" ");
                }

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

                Console.SetCursorPosition(food.col, food.row);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("@");

                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            byte right             = 0;
            byte left              = 1;
            byte down              = 2;
            byte up                = 3;
            int  lastFoodTime      = 0;
            int  foodDissapearTime = 8000;
            int  negativePoints    = 0;

            //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;
            lastFoodTime         = Environment.TickCount;

            //Linked List which is a linear data structure is used
            //Creating a linkedlist
            //Using List class
            //list to store position of obstacles
            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),
            };

            //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 (*)
            Queue <Position> snakeElements = new Queue <Position>();

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

            //The position is create randomly
            //creating food in the game
            Position food;

            do
            {
                food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                    randomNumbersGenerator.Next(0, Console.WindowWidth));
            }
            //new food will be created if snake eat food OR obstacle has the same position with food
            while (snakeElements.Contains(food) || obstacles.Contains(food));
            Console.SetCursorPosition(food.col, food.row);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("@");

            //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 >= 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))
                {
                    Console.SetCursorPosition(0, 0);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Game over!");
                    int userPoints = (snakeElements.Count - 6) * 100 - negativePoints;
                    //if (userPoints < 0) userPoints = 0;
                    userPoints = Math.Max(userPoints, 0);
                    Console.WriteLine("Your points are: {0}", userPoints); //displayed when game over
                    return;
                }

                //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)
                {
                    //feeding the snake
                    //generate new position for the food
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }
                    //if the snake eat the food or obstacles has the same position with food
                    while (snakeElements.Contains(food) || obstacles.Contains(food));
                    lastFoodTime = Environment.TickCount;
                    Console.SetCursorPosition(food.col, food.row);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("@"); //Creating food
                    sleepTime--;

                    Position obstacle = new Position();
                    //generate new position for the obstacles
                    do
                    {
                        obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                                randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(obstacle) || //if snake eat the obstacle
                            obstacles.Contains(obstacle) ||     //if obstacles appear at the same position
                            (food.row != obstacle.row && food.col != obstacle.row));
                    //the position of food and obstacle is different
                    obstacles.Add(obstacle); //then obstacle will be generated
                    Console.SetCursorPosition(obstacle.col, obstacle.row);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("=");
                }
                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
                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(" ");
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), //create new food
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }
                    //if snake eat food or obstacle and food appear at the same position
                    while (snakeElements.Contains(food) || obstacles.Contains(food));
                    lastFoodTime = Environment.TickCount; //The lastFoodTime will reset to the present time
                }

                Console.SetCursorPosition(food.col, food.row); //creating food
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("@");

                sleepTime -= 0.01;

                Thread.Sleep((int)sleepTime);
            }
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            byte right             = 0;
            byte left              = 1;
            byte down              = 2;
            byte up                = 3;
            int  lastFoodTime      = 0;
            int  foodDissapearTime = 16000;
            int  negativePoints    = 0;

            //Background music code
            SoundPlayer player = new SoundPlayer();

            player.SoundLocation = AppDomain.CurrentDomain.BaseDirectory + "\\Waltz-music-loop.wav";
            player.PlayLooping();

            //max - Creates an array that has four directions
            Position[] directions = new Position[]
            {
                new Position(0, 1),  // right
                new Position(0, -1), // left
                new Position(1, 0),  // down
                new Position(-1, 0), // up
            };
            //max - Sets the time to 100 milliseconds
            double sleepTime = 100;
            //max - Sets the direction of the snake
            int direction = right;
            //max - Randomly generate a number
            Random randomNumbersGenerator = new Random();

            //max - Set the height of the console
            Console.BufferHeight = Console.WindowHeight;
            //max - Set the time for the lastFoodTime
            lastFoodTime = Environment.TickCount;

            //philip - This List is to list out where would the obstacles will be appearing in the game by using X, Y Coordinator
            List <Position> obstacles = new List <Position>();

            for (int i = 0; i < 5; i++)
            {
                obstacles.Add(new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)));
            }

            //max - Setting the color, position and the 'symbol' (which is '=') of the obstacle.
            foreach (Position obstacle in obstacles)
            {
                SetObstacle(obstacle);
            }

            //ben - create 5 bodies of the snake
            Queue <Position> snakeElements = new Queue <Position>();

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

            //Philip - This part of code is to randomly spawn the food to any row and col,
            //while the food is eaten by snake or spawn at the obstacles' or snake's position, it will respawn again.
            Position food;

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

            //max - Setting the color, position and the 'symbol' (which is '*') of the snakeElements.
            foreach (Position position in snakeElements)
            {
                SetSnakeElement(position);
            }

            //ben - create an infinite loop for user input to change the direction
            while (true)
            {
                negativePoints++;

                int userPoint = (snakeElements.Count - 4) * 100 - negativePoints;
                if (userPoint < 0)
                {
                    userPoint = 0;
                }
                userPoint = Math.Max(userPoint, 0);

                Console.SetCursorPosition(0, 0);
                Console.Write("Score:{0}", userPoint);

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

                //philip - Snakeelements' last array number will be the snakeHead's position.
                Position snakeHead = snakeElements.Last();
                //nextDirection's value will be the direction's that is input by the user.
                Position nextDirection = directions[direction];
                //snakeNewHead will be using the if statement at line after 122 to calculate and get the result.
                Position snakeNewHead = new Position(snakeHead.row + nextDirection.row,
                                                     snakeHead.col + nextDirection.col);

                //max - allows the snake to appear at the bottom when the snake moves out of the top border vertically
                if (snakeNewHead.col < 0)
                {
                    snakeNewHead.col = Console.WindowWidth - 1;
                }
                //max - allows the snake to appear on the right side when the snake moves out of the left border horizontally
                if (snakeNewHead.row < 0)
                {
                    snakeNewHead.row = Console.WindowHeight - 1;
                }
                //max - allows the snake to appear on the left side when the snake moves out of the right border horizontally
                if (snakeNewHead.row >= Console.WindowHeight)
                {
                    snakeNewHead.row = 0;
                }
                //max - allows the snake to appear at the top when the snake moves out of the bottom border vertically
                if (snakeNewHead.col >= Console.WindowWidth)
                {
                    snakeNewHead.col = 0;
                }

                //ben - if snake head is collide with the body, show the word "Game over!" and show the points
                if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead))
                {
                    Lose();
                    Console.Read();
                    return;
                }

                //philip - Base on where the snakehead's position,produce gray color * for the snake body
                Console.SetCursorPosition(snakeHead.col, snakeHead.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");

                //max - Add the 'snakeNewHead' to the queue
                snakeElements.Enqueue(snakeNewHead);
                //max - Set the position of the snakeNewHead
                Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                //max - set the color of the snake head
                Console.ForegroundColor = ConsoleColor.Gray;
                //max - controls the direction of the snake
                if (direction == right)
                {
                    Console.Write(">");
                }
                if (direction == left)
                {
                    Console.Write("<");
                }
                if (direction == up)
                {
                    Console.Write("^");
                }
                if (direction == down)
                {
                    Console.Write("v");
                }

                //ben - if snake head reached the food, the snake elements increase by 1 and add a new food and an obstacle.
                if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
                {
                    //Soundeffect added.
                    SystemSounds.Beep.Play();
                    // feeding the snake
                    do
                    {
                        food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight),
                                            randomNumbersGenerator.Next(0, Console.WindowWidth));
                    }while (snakeElements.Contains(food) || obstacles.Contains(food));
                    // get the lastFoodTime (in Millisecond)
                    lastFoodTime = Environment.TickCount;

                    SetFood();

                    //decrease the sleepTime
                    sleepTime--;

                    // assign the obstacle to a random place (not in snake elements or obstacles)
                    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);
                    SetObstacle(obstacle);
                }
                else
                {
                    // moving...
                    //remove the last element of the snake elements and return it to the begining
                    Position last = snakeElements.Dequeue();
                    Console.SetCursorPosition(last.col, last.row);
                    //replace the last element with blank
                    Console.Write(" ");
                }
                //philip - This if statement is to reposition the food's position
                //from its last location if the tickcount is more than the foodDissapearTime
                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;
                }

                SetFood();

                //Add winning requirement
                if (snakeElements.Count == 7)
                {
                    Win();
                    Console.Read();
                    return;
                }

                //max - decrement the sleepTime by 0.01
                sleepTime -= 0.01;

                //max - The program will stop when it has reached the sleepTime
                Thread.Sleep((int)sleepTime);
            }

            // set the food postion,color,icon.
            void SetFood()
            {
                Console.SetCursorPosition(food.col, food.row);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("@");
            };

            // set the obstacle position,color,icon.
            void SetObstacle(Position obstacle)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.SetCursorPosition(obstacle.col, obstacle.row);
                Console.Write("=");
            }

            //set the snake element postion,color,icon
            void SetSnakeElement(Position position)
            {
                Console.SetCursorPosition(position.col, position.row);
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("*");
            }

            //lose
            void Lose()
            {
                //Set Game over to middle of the window
                Console.SetCursorPosition(54, 13);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Game over!");

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

                if (userPoints < 0)
                {
                    userPoints = 0;
                }

                //Set Score to middle of the window
                Console.SetCursorPosition(50, 14);
                userPoints = Math.Max(userPoints, 0);
                Console.WriteLine("Your points are: {0}", userPoints);

                //Add player score into plain text file.
                StreamWriter snakeFile = new StreamWriter("Snake_Score.txt", true);

                snakeFile.Write("Your high score is: " + userPoints + "\n");
                snakeFile.Close();

                //Set instruction to middle of window
                Console.SetCursorPosition(45, 15);
                Console.WriteLine("Press Enter to quit the game");
            }

            void Win()
            {
                Console.SetCursorPosition(54, 13);
                Console.WriteLine("YOU WIN!");

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

                if (userPoints < 0)
                {
                    userPoints = 0;
                }

                //Set Score to middle of the window
                Console.SetCursorPosition(50, 14);
                userPoints = Math.Max(userPoints, 0);
                Console.WriteLine("Your points are: {0}", userPoints);

                //Add player score into plain text file.
                StreamWriter snakeFile = new StreamWriter("Snake_Score.txt", true);

                snakeFile.Write("Your high score is: " + userPoints + "\n");
                snakeFile.Close();

                //Set instruction to middle of window
                Console.SetCursorPosition(45, 15);
                Console.WriteLine("Press Enter to quit the game");
            }
        }