feat: initial project structure with Snake.Core, CLI and Avalonia skeleton
This commit is contained in:
38
Snake.Core/Food.cs
Normal file
38
Snake.Core/Food.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
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)];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user