static void Main(string[] args) { if (args.Contains("--demo")) { var demo = new Demo(); demo.Run(); return; } var snake = new Snake(3, 3); var food = new Food() { X = 7, Y = 7 }; var board = new Board(DrawSnakeHead, RemoveSnakeTail, DrawFood, DrawBoard, snake, food); while (true) { Console.SetCursorPosition(board.Width + 2, board.Height + 2); Thread.Sleep(500); if (Console.KeyAvailable) { var key = Console.ReadKey(); if (key.Key == ConsoleKey.LeftArrow) { board.TurnSnake(Direction.West); } if (key.Key == ConsoleKey.RightArrow) { board.TurnSnake(Direction.East); } if (key.Key == ConsoleKey.UpArrow) { board.TurnSnake(Direction.North); } if (key.Key == ConsoleKey.DownArrow) { board.TurnSnake(Direction.South); } while (Console.KeyAvailable) { Console.ReadKey(false); } } if (!board.WalkSnake()) { Console.WriteLine("Game Over"); break; } } }
internal void Run() { while (true) { Console.Clear(); var snake = new Snake(3, 3); var food = new Food() { X = 7, Y = 7 }; var board = new Board(DrawSnakeHead, RemoveSnakeTail, DrawFood, DrawBoard, snake, food); while (true) { Console.SetCursorPosition(board.Width + 2, board.Height + 2); Thread.Sleep(100); var westScore = 0; if (board.IsWall(snake.Head.X - 1, snake.Head.Y) || snake.IsSnake(snake.Head.X - 1, snake.Head.Y)) { westScore = int.MinValue; } else { westScore = snake.Head.X - food.X; } var eastScore = 0; if (board.IsWall(snake.Head.X + 1, snake.Head.Y) || snake.IsSnake(snake.Head.X + 1, snake.Head.Y)) { eastScore = int.MinValue; } else { eastScore = food.X - snake.Head.X; } var northScore = 0; if (board.IsWall(snake.Head.X, snake.Head.Y - 1) || snake.IsSnake(snake.Head.X, snake.Head.Y - 1)) { northScore = int.MinValue; } else { northScore = snake.Head.Y - food.Y; } var southScore = 0; if (board.IsWall(snake.Head.X, snake.Head.Y + 1) || snake.IsSnake(snake.Head.X, snake.Head.Y + 1)) { southScore = int.MinValue; } else { southScore = food.Y - snake.Head.Y; } if (westScore >= eastScore && westScore >= northScore && westScore >= southScore) { board.TurnSnake(Direction.West); } else if (eastScore >= westScore && eastScore >= northScore && eastScore >= southScore) { board.TurnSnake(Direction.East); } else if (southScore >= westScore && southScore >= northScore && southScore >= eastScore) { board.TurnSnake(Direction.South); } else { board.TurnSnake(Direction.North); } if (!board.WalkSnake()) { ShowGameOver(); break; } } } }