fix: correct tail collision logic in SnakeGame and Snake
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user