fix: correct tail collision logic in SnakeGame and Snake
This commit is contained in:
@@ -55,8 +55,13 @@ public sealed class Snake
|
|||||||
return newHead;
|
return newHead;
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool Occupies(Position position) =>
|
public bool Occupies(Position position, bool excludeTail = false)
|
||||||
_segments.Contains(position);
|
{
|
||||||
|
if (excludeTail && _segments.Last is { } last && last.Value == position)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return _segments.Contains(position);
|
||||||
|
}
|
||||||
|
|
||||||
private static Position DirectionToOffset(Direction direction) =>
|
private static Position DirectionToOffset(Direction direction) =>
|
||||||
direction switch
|
direction switch
|
||||||
|
|||||||
@@ -39,14 +39,13 @@ public sealed class SnakeGame
|
|||||||
return GameTickResult.GameOver;
|
return GameTickResult.GameOver;
|
||||||
|
|
||||||
var newHead = Snake.PeekNextHead();
|
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;
|
IsGameOver = true;
|
||||||
return GameTickResult.GameOver;
|
return GameTickResult.GameOver;
|
||||||
}
|
}
|
||||||
|
|
||||||
var ateFood = newHead == Food.Position;
|
|
||||||
Snake.Move(grow: ateFood);
|
Snake.Move(grow: ateFood);
|
||||||
|
|
||||||
if (ateFood)
|
if (ateFood)
|
||||||
|
|||||||
Reference in New Issue
Block a user