Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Collections;
- using System.Threading;
- namespace JustSnake
- {
- struct Position
- {
- public int row;
- public int col;
- public Position(int row, int col)
- {
- this.row = row;
- this.col = col;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Position[] directions = new Position[]
- {
- new Position(0, 1), // right
- new Position(0, -1), // left
- new Position(1, 0), // down
- new Position(-1, 0), // top
- };
- int sleepTime = 100;
- int direction = 0; // 0
- Random randomnumbersGenerator = new Random();
- Console.BufferHeight = Console.WindowHeight;
- Position food = new Position(randomnumbersGenerator.Next(0, Console.WindowHeight), randomnumbersGenerator.Next(0, Console.WindowWidth));
- Queue<Position> snakeElements = new Queue<Position>();
- for (int i = 0; i <= 5; i++)
- {
- snakeElements.Enqueue(new Position(0, i));
- }
- while (true)
- {
- if (Console.KeyAvailable)
- {
- ConsoleKeyInfo userInput = Console.ReadKey();
- if (userInput.Key == ConsoleKey.LeftArrow)
- {
- direction = 1;
- }
- if (userInput.Key == ConsoleKey.RightArrow)
- {
- direction = 0;
- }
- if (userInput.Key == ConsoleKey.UpArrow)
- {
- direction = 3;
- }
- if (userInput.Key == ConsoleKey.DownArrow)
- {
- direction = 2;
- }
- // 0,1,2,3 индексирани от масива
- }
- Position snakeHead = snakeElements.Last();
- Position nextDirection = directions[direction];
- Position snakeNewHead = new Position(snakeHead.row + nextDirection.row, snakeHead.col + nextDirection.col);
- if (snakeNewHead.row < 0 ||
- snakeNewHead.col < 0 ||
- snakeNewHead.row >= Console.WindowHeight ||
- snakeNewHead.col >= Console.WindowWidth ||
- snakeElements.Contains(snakeNewHead))
- {
- Console.SetCursorPosition(0, 0);
- Console.WriteLine("Game over");
- Console.WriteLine("Your points are: {0}", ((snakeElements.Count-6) * 100));
- return; // приключва изпълнението на текущата функция - ще свърши програмата
- }
- snakeElements.Enqueue(snakeNewHead);
- if (snakeNewHead.col == food.col && snakeNewHead.row == food.row)
- {
- // feeding snake - може да забързваме тук змията
- food = new Position(randomnumbersGenerator.Next(0, Console.WindowHeight), randomnumbersGenerator.Next(0, Console.WindowWidth));
- sleepTime--;
- }
- else
- {
- // moving ...
- snakeElements.Dequeue();
- }
- Console.Clear();
- foreach (Position position in snakeElements)
- {
- Console.SetCursorPosition(position.col, position.row);
- Console.WriteLine("*");
- }
- Console.SetCursorPosition(food.col, food.row);
- Console.WriteLine("@");
- Thread.Sleep(sleepTime);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement