namespace Snake.Core; public sealed class Food { private readonly Random _random; public Food(Board board, IEnumerable 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 occupiedPositions) { var occupied = occupiedPositions.ToHashSet(); var freeCells = new List(); 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)]; } }