private void InitializeSnake() { Position p1 = new Position(0, 0); Position p2 = new Position(1, 0); Position p3 = new Position(2, 0); this.elements.Enqueue(p1); this.elements.Enqueue(p2); this.elements.Enqueue(p3); }
public void Move(Position direction) { var snakeHeadPosition = this.elements.Last(); var nextSnakePosition = new Position(snakeHeadPosition.x + direction.x, snakeHeadPosition.y + direction.y); this.elements.Enqueue(nextSnakePosition); if (!this.HasEatenApple) { this.elements.Dequeue(); } this.HasEatenApple = false; }
public void Run() { var snake = new Snake(); var previousDirection = new Position(1, 0); while (!snake.IsDead) { Position direction = this.GetDirection(previousDirection); previousDirection = direction; snake.Clear(this.Renderer); snake.Move(direction); snake.Render(this.Renderer); Thread.Sleep(100); } }
private Position GetDirection(Position previousDirection) { var right = new Position(1, 0); var down = new Position(0, 1); var left = new Position(-1, 0); var up = new Position(0, -1); if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(); if (key.Key == ConsoleKey.LeftArrow) { if (!previousDirection.CompareTo(right)) { return left; } } if (key.Key == ConsoleKey.UpArrow) { if (!previousDirection.CompareTo(down)) { return up; } } if (key.Key == ConsoleKey.RightArrow) { if (!previousDirection.CompareTo(left)) { return right; } } if (key.Key == ConsoleKey.DownArrow) { if (!previousDirection.CompareTo(up)) { return down; } } } return previousDirection; }