From 8c9d52a0a43618a9a21ca3690d7a27c043d014ea Mon Sep 17 00:00:00 2001 From: Dan Barber Date: Mon, 12 Mar 2018 15:39:16 -0400 Subject: [PATCH] King moves --- lib/chess/moves.ex | 3 ++- lib/chess/moves/king.ex | 15 +++++++++++++++ test/chess/moves/king_test.exs | 29 +++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 lib/chess/moves/king.ex create mode 100644 test/chess/moves/king_test.exs diff --git a/lib/chess/moves.ex b/lib/chess/moves.ex index b863d9e..da153ae 100644 --- a/lib/chess/moves.ex +++ b/lib/chess/moves.ex @@ -6,6 +6,7 @@ defmodule Chess.Moves do alias Chess.Moves.Knight alias Chess.Moves.Rook alias Chess.Moves.Queen + alias Chess.Moves.King def available(board, {file, rank}) do piece = board["#{file},#{rank}"] @@ -20,7 +21,7 @@ defmodule Chess.Moves do %{"type" => "knight"} -> Knight.moves(board, {file, rank}) %{"type" => "king"} -> - [] + King.moves(board, {file, rank}) %{"type" => "queen"} -> Queen.moves(board, {file, rank}) end diff --git a/lib/chess/moves/king.ex b/lib/chess/moves/king.ex new file mode 100644 index 0000000..a556235 --- /dev/null +++ b/lib/chess/moves/king.ex @@ -0,0 +1,15 @@ +defmodule Chess.Moves.King do + @moduledoc false + + def moves(_board, {file, rank}) do + patterns + |> Enum.map(fn ({fv, rv}) -> {file + fv, rank + rv} end) + |> Enum.reject(fn ({file, rank}) -> + file < 0 || rank < 0 || file > 7 || rank > 7 + end) + end + + defp patterns do + [{1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}] + end +end diff --git a/test/chess/moves/king_test.exs b/test/chess/moves/king_test.exs new file mode 100644 index 0000000..5cc8b2b --- /dev/null +++ b/test/chess/moves/king_test.exs @@ -0,0 +1,29 @@ +defmodule Chess.Moves.KingTest do + use Chess.DataCase + + alias Chess.Moves + + test "kings can move one square in any direction" do + board = %{"4,5" => %{"type" => "king", "colour" => "white"}} + moves = Moves.available(board, {4, 5}) + + expected_moves = Enum.sort([ + {3, 4}, {4, 4}, {5, 4}, {5, 5}, {5, 6}, {4, 6}, {3, 6}, {3, 5}, + ]) + assert Enum.sort(moves) == expected_moves + end + + test "knights cannot move beyond the edges of the board" do + board = %{"0,0" => %{"type" => "knight", "colour" => "white"}} + moves = Moves.available(board, {0, 0}) + + expected_moves = Enum.sort([ + {1, 2}, {2, 1} + ]) + assert Enum.sort(moves) == expected_moves + end + + def board do + Chess.Board.default + end +end