From 87c453c5646a79093343f06f281ac6566d82fe2e Mon Sep 17 00:00:00 2001 From: Dan Barber Date: Tue, 8 May 2018 14:06:43 +0200 Subject: [PATCH] Translate moves into display format --- lib/chess/moves.ex | 7 +++++++ lib/chess/store/move.ex | 8 ++++++++ test/chess/moves_test.exs | 34 ++++++++++++++++++++++++++++++++++ test/chess/store/move_test.exs | 10 ++++++++++ 4 files changed, 59 insertions(+) create mode 100644 test/chess/moves_test.exs diff --git a/lib/chess/moves.ex b/lib/chess/moves.ex index 56e2ac2..d9d8672 100644 --- a/lib/chess/moves.ex +++ b/lib/chess/moves.ex @@ -2,6 +2,7 @@ defmodule Chess.Moves do @moduledoc false alias Chess.Board + alias Chess.Store.Move alias Chess.Moves.Pieces.Pawn alias Chess.Moves.Pieces.Bishop @@ -10,6 +11,12 @@ defmodule Chess.Moves do alias Chess.Moves.Pieces.Queen alias Chess.Moves.Pieces.King + def transform(moves) do + moves + |> Enum.map(fn(move) -> Move.translate(move) end) + |> Enum.chunk_every(2) + end + def available(board, {file, rank}) do piece = board diff --git a/lib/chess/store/move.ex b/lib/chess/store/move.ex index 0a5bcfb..6603e93 100644 --- a/lib/chess/store/move.ex +++ b/lib/chess/store/move.ex @@ -27,5 +27,13 @@ defmodule Chess.Store.Move do |> validate_required(required_attrs()) end + def translate(move) do + [ + <<97 + move.from.file, 49 + move.from.rank>>, + <<97 + move.to.file, 49 + move.to.rank>> + ] + |> Enum.join("-") + end + defp required_attrs, do: ~w[game_id from to piece]a end diff --git a/test/chess/moves_test.exs b/test/chess/moves_test.exs new file mode 100644 index 0000000..fffec9c --- /dev/null +++ b/test/chess/moves_test.exs @@ -0,0 +1,34 @@ +defmodule Chess.MovesTest do + @moduledoc false + + use Chess.DataCase + + describe "moves" do + alias Chess.Store.Move + alias Chess.Moves + + test "tranforms a list of moves" do + moves = [ + %Move{ + from: %{file: 4, rank: 1}, + to: %{file: 4, rank: 3}, + }, + %Move{ + from: %{file: 4, rank: 6}, + to: %{file: 4, rank: 4}, + }, + %Move{ + from: %{file: 1, rank: 0}, + to: %{file: 2, rank: 2}, + }, + ] + + expected_result = [ + ["e2-e4", "e7-e5"], + ["b1-c3"], + ] + + assert Moves.transform(moves) == expected_result + end + end +end diff --git a/test/chess/store/move_test.exs b/test/chess/store/move_test.exs index 3265b1d..f4ef53a 100644 --- a/test/chess/store/move_test.exs +++ b/test/chess/store/move_test.exs @@ -77,5 +77,15 @@ defmodule Chess.MoveTest do refute changeset.valid? end + + + test "translates a move" do + move = %Move{ + from: %{file: 4, rank: 1}, + to: %{file: 4, rank: 3}, + } + + assert Move.translate(move) == "e2-e4" + end end end