39 lines
1.0 KiB
C#
39 lines
1.0 KiB
C#
namespace Snake.Core;
|
|
|
|
public sealed class Food
|
|
{
|
|
private readonly Random _random;
|
|
|
|
public Food(Board board, IEnumerable<Position> occupiedPositions, Random? random = null)
|
|
{
|
|
_random = random ?? Random.Shared;
|
|
Board = board;
|
|
Respawn(occupiedPositions);
|
|
}
|
|
|
|
public Board Board { get; }
|
|
|
|
public Position Position { get; private set; }
|
|
|
|
public void Respawn(IEnumerable<Position> occupiedPositions)
|
|
{
|
|
var occupied = occupiedPositions.ToHashSet();
|
|
var freeCells = new List<Position>();
|
|
|
|
for (var y = 0; y < Board.Height; y++)
|
|
{
|
|
for (var x = 0; x < Board.Width; x++)
|
|
{
|
|
var position = new Position(x, y);
|
|
if (!occupied.Contains(position))
|
|
freeCells.Add(position);
|
|
}
|
|
}
|
|
|
|
if (freeCells.Count == 0)
|
|
throw new InvalidOperationException("No free cells available for food.");
|
|
|
|
Position = freeCells[_random.Next(freeCells.Count)];
|
|
}
|
|
}
|