Add Day 6
This commit is contained in:
parent
0111ee1176
commit
367cd56a42
9 changed files with 345 additions and 0 deletions
68
src/2024/06/Guard.cs
Normal file
68
src/2024/06/Guard.cs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
class Guard : IUpdate
|
||||
{
|
||||
private readonly Map _map;
|
||||
private readonly HashSet<(Vector2I, char)> _path = [];
|
||||
|
||||
public char Direction { get; set; }
|
||||
|
||||
public Vector2I Position { get; set; }
|
||||
|
||||
public Guard(Map map)
|
||||
{
|
||||
_map = map;
|
||||
map.RegisterOnUpdate(this);
|
||||
}
|
||||
|
||||
public bool? Step()
|
||||
{
|
||||
if (!_path.Add((Position, Direction)))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
var test = NextPosition();
|
||||
if (!_map.IsValid(test))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if (_map.IsOccupied(test))
|
||||
{
|
||||
Direction = Turn();
|
||||
}
|
||||
else
|
||||
{
|
||||
Position = test;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Update()
|
||||
{
|
||||
var tmpPosition = Position;
|
||||
if (Step() is not true)
|
||||
{
|
||||
_map.UnregisterOnUpdate(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
_map.Move(tmpPosition, Position);
|
||||
}
|
||||
}
|
||||
|
||||
private Vector2I NextPosition()
|
||||
{
|
||||
return Position + Program.ToVector(Direction);
|
||||
}
|
||||
|
||||
private char Turn()
|
||||
{
|
||||
return Direction switch
|
||||
{
|
||||
'^' => '>',
|
||||
'>' => 'v',
|
||||
'v' => '<',
|
||||
'<' => '^',
|
||||
_ => throw new InvalidOperationException()
|
||||
};
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue