Thinking of implementing a Chess game in Elixir, I created a module which will represent a chess piece as a struct.
defmodule Piece do
alias __MODULE__, as: Piece
@piece_types ~w(King Queen Rook Bishop Knight Pawn)a
@type type :: :King | :Queen | :Rook | :Bishop | :Knight | :Pawn
defstruct [:type]
@type t :: %Piece{ type: type() }
defguard is_type(piece_type) when piece_type in @piece_types
def new(type) when is_type(type), do: %Piece{type: type}
end
then there is a struct that represents an active piece:
defmodule Fighter do
alias __MODULE__, as: Fighter
@type owner :: :player | :opponent
defstruct [ :owner, :piece, :position ]
@type t :: %Fighter{ owner: owner(), piece: Piece.t(), position: BoardCoordinate.t }
end
So I have a List of Fighter
s when the game starts. I came to a circumstance where I want to sort the Fighter
s.
The result should be sorted first by fighter.owner
, then by fighter.piece.type
, and then by fighter.position
, so it will be
- my king
- my queen
… - my most left-top pawn
- my secondly left-top pawn
… - opponent’s king
- opponent’s queen
…
and so on. Can I perform this on a single custom sort? (Like performing fighters |> Fighter.sort()
)?
For that I thought setting a default sort algorism for each struct type could be a simple way, but I couldn’t have sorted(!) this out.
Any help and thoughts are welcomed!