diff --git a/Snake.Core/Snake.cs b/Snake.Core/Snake.cs index e88c5bc..b554871 100644 --- a/Snake.Core/Snake.cs +++ b/Snake.Core/Snake.cs @@ -55,8 +55,13 @@ public sealed class Snake return newHead; } - public bool Occupies(Position position) => - _segments.Contains(position); + public bool Occupies(Position position, bool excludeTail = false) + { + if (excludeTail && _segments.Last is { } last && last.Value == position) + return false; + + return _segments.Contains(position); + } private static Position DirectionToOffset(Direction direction) => direction switch diff --git a/Snake.Core/SnakeGame.cs b/Snake.Core/SnakeGame.cs index cc44090..73be79d 100644 --- a/Snake.Core/SnakeGame.cs +++ b/Snake.Core/SnakeGame.cs @@ -39,14 +39,13 @@ public sealed class SnakeGame return GameTickResult.GameOver; var newHead = Snake.PeekNextHead(); + var ateFood = newHead == Food.Position; - if (!Board.IsWithinBounds(newHead) || Snake.Occupies(newHead)) + if (!Board.IsWithinBounds(newHead) || Snake.Occupies(newHead, excludeTail: !ateFood)) { IsGameOver = true; return GameTickResult.GameOver; } - - var ateFood = newHead == Food.Position; Snake.Move(grow: ateFood); if (ateFood)