private bool CheckCollision(StateOfLocation[,] oldGameBoard, List <Point> newSnakePosition) { Point snakeHeadPosition = newSnakePosition[0]; //Does the snake run out of the game area? if (snakeHeadPosition.Y < 0 || snakeHeadPosition.Y > height - 1 || snakeHeadPosition.X < 0 || snakeHeadPosition.X > width - 1) { return(true); } //Does the snake run into itself? if (oldGameBoard[snakeHeadPosition.X, snakeHeadPosition.Y] == StateOfLocation.Snake) { return(true); } //Does the snake run into food? if (oldGameBoard[snakeHeadPosition.X, snakeHeadPosition.Y] == StateOfLocation.Food) { snake.Eat(); score++; hasEaten = true; food.ChangeFoodPosition(width, height, gameBoard); return(false); } //Does the snake go into empty space? return(false); }
static void Main() { Console.CursorVisible = false; DrawFrame(); bool exit = false; double refreshRate = 1000 / 5.0; DateTime lastTime = DateTime.Now; Food food = new Food(); SnakeClass snake = new SnakeClass(); while (!exit) { if (Console.KeyAvailable) { ConsoleKeyInfo input = Console.ReadKey(); switch (input.Key) { case ConsoleKey.Escape: snake.gameOver = true; break; case ConsoleKey.UpArrow: if (snake.Direction != Direction.down) { snake.Direction = Direction.up; } break; case ConsoleKey.DownArrow: if (snake.Direction != Direction.up) { snake.Direction = Direction.down; } break; case ConsoleKey.LeftArrow: if (snake.Direction != Direction.right) { snake.Direction = Direction.left; } break; case ConsoleKey.RightArrow: if (snake.Direction != Direction.left) { snake.Direction = Direction.right; } break; } } if ((DateTime.Now - lastTime).TotalMilliseconds >= refreshRate) { snake.Move(); if (snake.HeadPosition.X == food.foodCoordinates.X && snake.HeadPosition.Y == food.foodCoordinates.Y) { snake.Eat(); food = new Food(); refreshRate /= 1.1; } if (snake.gameOver) { exit = true; Console.Clear(); Console.WriteLine($"Game over! Your score: {snake.Length-1}"); Console.ReadLine(); } lastTime = DateTime.Now; } } }