I am getting a StackOverflowException on the get;
of a property in an abstract class.
public abstract class SenseHatSnake
{
privat
This is a bad pattern:
protected SenseHatSnake(ISenseHat senseHat)
{
SenseHat = senseHat;
}
protected static ISenseHat SenseHat { get; set; }
// ^^^^^^
Your constructor is setting a static field shared among all subclasses of SenseHatSnake
, meaning that the last class setting the field "wins". It also means that you can never set this field, because in order to construct the value to assign to the field you must create an object that has to have that field set - a snake chasing its own tail. Also you cannot derive Movement
from a class that constructs a member of type Movement
as part of its initialization.
Fixing this requires some serious re-organization of your classes:
public class SnakeGame {
private readonly int _gameSpeed = 1000;
private static Timer _updatePositionTimer;
private bool _gameOver = false;
public Movement Movement {get;}
public Food Food {get;}
public Body Body {get;}
public Display Display {get;}
public Draw Draw {get;}
public SnakeGame(ISenseHat senseHat)
{
Movement = new Movement(this);
Food = new Food(this);
Body = new Body(this);
Display = new Display(this);
Draw = new Draw(this);
}
//More code
}
public abstract class GameObject {
protected readonly SnakeGame game;
protected GameObject(SnakeGame game) {
this.game = game;
}
}
public class Movement : GameObject
{
public Movement(SnakeGame game)
: base(senseHat)
{
}
//More code
}
Now subclasses of GameObject
share SnakeGame
object, gaining access to its properties.