Esempio n. 1
0
 private void ResetOptions()
 {
     food  = new Food();
     snake = new Snake();
     snake.SnakeFormWidth  = this.ClientRectangle.Width;
     snake.SnakeFormHeight = this.ClientRectangle.Height;
     score     = new Scoreboard();
     direction = "right";
 }
Esempio n. 2
0
        static void Main(string[] args)
        {
            do
            {
                Console.ForegroundColor = ConsoleColor.White;
                MainMenu start   = new MainMenu();
                string   command = "";
                do
                {
                    if (Console.KeyAvailable)
                    {
                        command = start.Choice();
                    }
                } while (command == "");


                Console.Clear();
                // exit prohrmm
                if (command == "exit")
                {
                    return;
                }

                Random randomNumbersGenerator = new Random(); // RANDOM NUMBER
                Console.BufferHeight  = Console.WindowHeight;
                Console.CursorVisible = false;



                // USER MANAGEMENT SYSTEM
                Console.WriteLine("Enter username: "******"Hello, " + currUser.name + "! Press ENTER to start");
                Console.ReadLine();
                Console.Clear();

                //FOR WALL DETAILS - HEIGHT
                for (int i = 0; i < Console.WindowWidth; i++)
                {
                    Console.SetCursorPosition(i, 2);
                    Console.Write("\u2592");
                    Console.SetCursorPosition(i, Console.WindowHeight - 1);
                    Console.Write("\u2592");
                }

                //FOR WALL DETAILS - WIDTH
                for (int j = 1; j < Console.WindowHeight - 1; j++)
                {
                    Console.SetCursorPosition(0, j);
                    Console.Write("\u2592");
                    Console.SetCursorPosition(Console.WindowWidth - 1, j);
                    Console.Write("\u2592");
                }


                // INITIALISE & DISPLAY 5 OBSTACLES
                // added to ObstacleList list
                ObstacleList ObstacleList = new ObstacleList();
                for (int i = 0; i < 5; i++)
                {
                    ObstacleList.AddObstacle(new Obstacle(new Position(randomNumbersGenerator.Next(5, Console.WindowHeight - 4), randomNumbersGenerator.Next(5, Console.WindowWidth - 3))));
                }
                foreach (Obstacle ob in ObstacleList.Obstacles)
                {
                    ob.Display();
                }                                                                 // Dislay Obstacles


                // INITIALISE SNAKE ELEMENTS
                Snake snake = new Snake();

                // INITIALISE SNAKE DIRECTION
                Directions direction = new Directions(Arrow.right);

                // INITIALISE FOOD POSITION
                Food food = new Food();;
                food.UpdateFoodPosition(snake, ObstacleList, randomNumbersGenerator);
                food.Display();


                // INITIALISE USER POINTS
                int userPoints = 0;

                // INITIALISE SOUNDS
                string      path  = Path.Combine(Directory.GetCurrentDirectory(), "repeat.wav");
                SoundPlayer sound = new SoundPlayer(path);
                sound.PlayLooping();

                //INITIALISE AND DISPLAY SNAKE LIVES
                string heartSymbol = "\u2660";
                int    lives       = snake.getSnakeLives();
                string ss1         = "HP : " + String.Concat(Enumerable.Repeat(heartSymbol, lives));
                Console.SetCursorPosition((Console.WindowWidth - 10), 0);
                Console.WriteLine(ss1);

                // PROGAM STARTS HERE
                while (userPoints < 500)
                {
                    // Update Snake's current direction when a key is pressed
                    if (Console.KeyAvailable)
                    {
                        direction.ChangeDirection();
                    }

                    // Update Snake's position
                    Position snakeNewHead = snake.UpdatePosition(direction.CurrentDirection);

                    //  GAME OVER
                    if (snake.SnakeElements.Contains(snakeNewHead) || ObstacleList.Position.Contains(snakeNewHead))
                    {
                        if (lives == 1)
                        {
                            break;
                        }
                        else
                        {
                            lives--;
                        }
                    }
                    Console.SetCursorPosition((Console.WindowWidth - 10), 0);
                    Console.WriteLine("          ");
                    Console.SetCursorPosition((Console.WindowWidth - 10), 0);
                    ss1 = "HP : " + String.Concat(Enumerable.Repeat(heartSymbol, lives));
                    Console.WriteLine(ss1);


                    snake.Display();

                    // Update Snake's Head
                    snake.AddElement(snakeNewHead);
                    Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row);
                    Console.ForegroundColor = ConsoleColor.Gray;
                    if (direction.Arrow == Arrow.right)
                    {
                        Console.Write(">");
                    }
                    if (direction.Arrow == Arrow.left)
                    {
                        Console.Write("<");
                    }
                    if (direction.Arrow == Arrow.up)
                    {
                        Console.Write("^");
                    }
                    if (direction.Arrow == Arrow.down)
                    {
                        Console.Write("v");
                    }


                    // WHEN FOOD IS EATEN
                    if (snakeNewHead == food.Pos)
                    {
                        // Reposition Food after eaten
                        userPoints += food.GetFoodPoints;
                        food.UpdateFoodPosition(snake, ObstacleList, randomNumbersGenerator);

                        // Randomly place new obstacle
                        ObstacleList.PositionNewObstacle(snake, food, randomNumbersGenerator);
                    }


                    // WHEN FOOD IS NOT EATEN
                    else
                    {
                        // moving...
                        Position last = snake.SnakeElements.Dequeue();
                        Console.SetCursorPosition(last.col, last.row);
                        Console.Write(" ");

                        // REPOSITION FOOD IF NOT EATEN
                        if (Environment.TickCount - food.LastFoodTime >= food.DisappearTime)
                        {
                            //negativePoints = 50;
                            Console.SetCursorPosition(food.Col, food.Row);
                            Console.Write(" ");
                            food.UpdateFoodPosition(snake, ObstacleList, randomNumbersGenerator);
                            userPoints -= 50;
                        }
                    }
                    Console.SetCursorPosition(Console.WindowWidth / 2, 0);
                    Console.WriteLine("Food disappear in:   ");
                    Console.SetCursorPosition(Console.WindowWidth / 2, 0);
                    Console.WriteLine("Food disappear in: " + (10 - ((Environment.TickCount - food.LastFoodTime) / 1000)));
                    food.Display();

                    //SPEED UP SNAKE AFTER POINTS REACHED 200
                    if (userPoints > 200)
                    {
                        snake.SleepTime -= 0.05; // Increase Snake's speed
                    }


                    snake.SleepTime -= 0.01;            // Increase Snake's speed

                    Thread.Sleep((int)snake.SleepTime); // Update Program's speed
                    userPoints = Math.Max(userPoints, 0);
                    Console.SetCursorPosition(0, 0);

                    Console.WriteLine("Your points are:    ");

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

                // STORES PLAYER'S DATA IN "UserData.txt"
                currUser.score = userPoints;
                Scoreboard scoreboard = new Scoreboard();
                scoreboard.updateScoreboard(currUser);
                scoreboard.updateFile();
                scoreboard.DisplayScoreboard();

                if (userPoints >= 500)
                {
                    string      path3  = Path.Combine(Directory.GetCurrentDirectory(), "yay.wav");
                    SoundPlayer sound3 = new SoundPlayer(path3);
                    sound3.Play();

                    string s3 = "You won, " + currUser.name + "! Your score is {0} \n";
                    Console.SetCursorPosition((Console.WindowWidth - s3.Length) / 2, 0);

                    Console.Write(s3, userPoints);
                    Console.ReadLine();
                }
                else
                {
                    string s1 = "Game over, " + currUser.name + "!";
                    string s2 = "Your points are: {0}";
                    Console.SetCursorPosition((Console.WindowWidth - s1.Length) / 2, (Console.WindowHeight - 2) / 2);
                    Console.ForegroundColor = ConsoleColor.Red;



                    string      path2  = Path.Combine(Directory.GetCurrentDirectory(), "aww.wav");
                    SoundPlayer sound2 = new SoundPlayer(path2);
                    sound2.Play();

                    Console.WriteLine(s1);


                    userPoints = Math.Max(userPoints, 0);
                    Console.SetCursorPosition((Console.WindowWidth - s2.Length) / 2, ((Console.WindowHeight) / 2));
                    Console.WriteLine(s2, userPoints);
                    Console.SetCursorPosition((Console.WindowWidth - s2.Length) / 2, ((Console.WindowHeight + 2) / 2));
                    Console.WriteLine("Press Enter to Return to Main Menu");
                    Console.ReadLine();
                }
                Console.Clear();
            } while (true);
        }
Esempio n. 3
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);
            }
        }
Esempio n. 4
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);
                }
            }
        }
Esempio n. 5
0
        //Main Program
        static void Main(string[] args)
        {
            Console.WindowHeight = 30;
            Console.WindowWidth  = 130;

            // Set the Foreground color to blue
            Console.BackgroundColor
                = ConsoleColor.White;

            // Display current Foreground color
            Console.ForegroundColor = ConsoleColor.Black;
            //prevents from cursor showing
            Console.CursorVisible = false;
            byte   right             = 0;
            byte   left              = 1;
            byte   down              = 2;
            byte   up                = 3;
            int    lastFoodTime      = 0;
            int    negativePoints    = 0;
            int    foodDissapearTime = 0;
            double sleepTime         = 0;
            int    score             = 0;

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

            Console.Beep(1188, 250); Console.Beep(1056, 250); Console.Beep(990, 500); Console.Beep(990, 250); Console.Beep(1056, 250); Console.Beep(1188, 500); Console.Beep(1320, 500); Console.Beep(1056, 500); Console.Beep(880, 500); Console.Beep(880, 500);

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

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