Okay, I have no idea why this happens.
I set a property and just after I set it, it's null in an other class. Stepping though it with the debugger just shows it's set, and that its null in the other class.
This is my code: (stripped away all unnecessary code)
public class SnakeGame : SenseHatSnake, ISnakeGame
{
private readonly IBody _body;
public SnakeGame(ISenseHat senseHat, IBody body)
: base(senseHat)
{
_body = body;
}
private void UpdateGame(Object state)
{
_movement.PreviousPositions.Add(new Position()
{
X = _movement.X,
Y = _movement.Y
});
if (_body.DetectCollision(_movement.X, _movement.Y))
{
GameOver();
}
}
}
It happens at DetectCollision in the body class.
public class Body : IBody
{
private readonly IMovement _movement;
public Body(IMovement movement)
{
_movement = movement;
}
public bool DetectCollision(int x, int y)
{
for (int i = 1; i < Length + 1; i++)
{
if (_movement.PreviousPositions.Count > i)
{
int bX = _movement.PreviousPositions[_movement.PreviousPositions.Count - i - 1].X;
int bY = _movement.PreviousPositions[_movement.PreviousPositions.Count - i - 1].Y;
if (bX == x && bY == y)
{
return true;
}
}
}
return false;
}
}
I have just set the _movement.PreviousPositions and I can see it in debugger, but as soon it's in Body _movement.PreviousPositions is null.
Movement.cs:
public class Movement : IMovement
{
public List<Position> PreviousPositions { get; set; }
}
Note:
I am using DI, am I doing something wrong there? (Autofac)
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
var builder = new ContainerBuilder();
builder.RegisterType<Body>().As<IBody>();
builder.RegisterType<Display>().As<IDisplay>();
builder.RegisterType<Draw>().As<IDraw>();
builder.RegisterType<Food>().As<IFood>();
builder.RegisterType<Movement>().As<IMovement>();
builder.RegisterType<SnakeGame>().As<ISnakeGame>();
builder.RegisterType<ISenseHat>().As<ISenseHat>();
var container = builder.Build();
var body = container.Resolve<IBody>();
var display = container.Resolve<IDisplay>();
var draw = container.Resolve<IDraw>();
var food = container.Resolve<IFood>();
var movement = container.Resolve<IMovement>();
Task.Run(async () =>
{
ISenseHat senseHat = await SenseHatFactory.GetSenseHat().ConfigureAwait(false);
var snakeGame = new SnakeGame(senseHat, body, display, draw, food, movement);
snakeGame.Run();
});
}
}