feat: initial project structure with Snake.Core, CLI and Avalonia skeleton
This commit is contained in:
60
Snake.Core/SnakeGame.cs
Normal file
60
Snake.Core/SnakeGame.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
namespace Snake.Core;
|
||||
|
||||
public sealed class SnakeGame
|
||||
{
|
||||
public SnakeGame(int width, int height, Random? random = null)
|
||||
{
|
||||
_random = random ?? Random.Shared;
|
||||
Board = new Board(width, height);
|
||||
|
||||
var start = new Position(width / 2, height / 2);
|
||||
Snake = new Snake(start, length: 3, Direction.Right);
|
||||
Food = new Food(Board, Snake.Segments, _random);
|
||||
}
|
||||
|
||||
private readonly Random _random;
|
||||
|
||||
public Board Board { get; }
|
||||
|
||||
public Snake Snake { get; }
|
||||
|
||||
public Food Food { get; }
|
||||
|
||||
public int Score { get; private set; }
|
||||
|
||||
public bool IsGameOver { get; private set; }
|
||||
|
||||
public void SetDirection(Direction direction) => Snake.SetDirection(direction);
|
||||
|
||||
public GameTickResult Tick()
|
||||
{
|
||||
if (IsGameOver)
|
||||
return GameTickResult.GameOver;
|
||||
|
||||
var newHead = Snake.PeekNextHead();
|
||||
|
||||
if (!Board.IsWithinBounds(newHead) || Snake.Occupies(newHead))
|
||||
{
|
||||
IsGameOver = true;
|
||||
return GameTickResult.GameOver;
|
||||
}
|
||||
|
||||
var ateFood = newHead == Food.Position;
|
||||
Snake.Move(grow: ateFood);
|
||||
|
||||
if (ateFood)
|
||||
{
|
||||
Score++;
|
||||
if (Snake.Segments.Count >= Board.Width * Board.Height)
|
||||
{
|
||||
IsGameOver = true;
|
||||
return GameTickResult.AteFood;
|
||||
}
|
||||
|
||||
Food.Respawn(Snake.Segments);
|
||||
return GameTickResult.AteFood;
|
||||
}
|
||||
|
||||
return GameTickResult.Moved;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user