|
| 1 | +namespace Salvo; |
| 2 | + |
| 3 | +internal record struct Position(Coordinate X, Coordinate Y) |
| 4 | +{ |
| 5 | + public bool IsInRange => X.IsInRange && Y.IsInRange; |
| 6 | + public bool IsOnDiagonal => X == Y; |
| 7 | + |
| 8 | + public static Position Create((float X, float Y) coordinates) => new(coordinates.X, coordinates.Y); |
| 9 | + |
| 10 | + public static bool TryCreateValid((float X, float Y) coordinates, out Position position) |
| 11 | + { |
| 12 | + if (Coordinate.TryCreateValid(coordinates.X, out var x) && Coordinate.TryCreateValid(coordinates.Y, out var y)) |
| 13 | + { |
| 14 | + position = new(x, y); |
| 15 | + return true; |
| 16 | + } |
| 17 | + |
| 18 | + position = default; |
| 19 | + return false; |
| 20 | + } |
| 21 | + |
| 22 | + public static IEnumerable<Position> All |
| 23 | + => Coordinate.Range.SelectMany(x => Coordinate.Range.Select(y => new Position(x, y))); |
| 24 | + |
| 25 | + public IEnumerable<Position> Neighbours |
| 26 | + { |
| 27 | + get |
| 28 | + { |
| 29 | + foreach (var offset in Offset.Units) |
| 30 | + { |
| 31 | + var neighbour = this + offset; |
| 32 | + if (neighbour.IsInRange) { yield return neighbour; } |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + internal float DistanceTo(Position other) |
| 38 | + { |
| 39 | + var (deltaX, deltaY) = (X - other.X, Y - other.Y); |
| 40 | + return (float)Math.Sqrt(deltaX * deltaX + deltaY * deltaY); |
| 41 | + } |
| 42 | + |
| 43 | + internal Position BringIntoRange(IRandom random) |
| 44 | + => IsInRange ? this : new(X.BringIntoRange(random), Y.BringIntoRange(random)); |
| 45 | + |
| 46 | + public static Position operator +(Position position, Offset offset) |
| 47 | + => new(position.X + offset.X, position.Y + offset.Y); |
| 48 | + |
| 49 | + public static implicit operator Position(int value) => new(value, value); |
| 50 | + |
| 51 | + public override string ToString() => $"{X}{Y}"; |
| 52 | +} |
0 commit comments