Skip to content

Instantly share code, notes, and snippets.

@aroman
Created April 28, 2022 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aroman/680ec8669af54fd170b6f6902f9bebbf to your computer and use it in GitHub Desktop.
Save aroman/680ec8669af54fd170b6f6902f9bebbf to your computer and use it in GitHub Desktop.
using System;
using MessagePack;
namespace Simulation.Features.Buildings
{
[Serializable]
[MessagePackObject]
public readonly struct Cell : IEquatable<Cell>, IComparable<Cell>
{
[Key(0)] public readonly int x;
[Key(1)] public readonly int y;
private readonly int _hashCode;
public override string ToString() => $"Cell(x={x}, y={y})";
public Cell(int x, int y)
{
this.x = x;
this.y = y;
_hashCode = HashUtils.CombineHashCodes(x.GetHashCode(), y.GetHashCode());
}
public bool Equals(Cell other)
{
return x == other.x && y == other.y;
}
public override bool Equals(object obj)
{
return !ReferenceEquals(null, obj) && Equals((Cell)obj);
}
public static bool operator !=(Cell a, Cell b)
{
return !a.Equals(b);
}
public static bool operator ==(Cell a, Cell b)
{
return a.Equals(b);
}
public static Cell operator +(Cell a, Cell b)
{
return new Cell(a.x + b.x, a.y + b.y);
}
public override int GetHashCode() => _hashCode;
public int CompareTo(Cell other)
{
return _hashCode.CompareTo(other._hashCode);
}
}
public static class CellRelativePositionExtensions
{
public static Cell Above(this Cell cell)
{
return new Cell(cell.x, cell.y + 1);
}
public static Cell Below(this Cell cell)
{
return new Cell(cell.x, cell.y - 1);
}
public static Cell Left(this Cell cell)
{
return new Cell(cell.x - 1, cell.y);
}
public static Cell Right(this Cell cell)
{
return new Cell(cell.x + 1, cell.y);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment