From 3a421ca213153261baaf900657cf3df85e447409 Mon Sep 17 00:00:00 2001 From: Dan Barber Date: Mon, 12 Mar 2018 14:58:08 -0400 Subject: [PATCH] Knight moves --- lib/chess/moves.ex | 5 +++-- lib/chess/moves/knight.ex | 15 +++++++++++++++ test/chess/moves/knight_test.exs | 29 +++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 lib/chess/moves/knight.ex create mode 100644 test/chess/moves/knight_test.exs diff --git a/lib/chess/moves.ex b/lib/chess/moves.ex index c61f03b..b863d9e 100644 --- a/lib/chess/moves.ex +++ b/lib/chess/moves.ex @@ -2,8 +2,9 @@ defmodule Chess.Moves do @moduledoc false alias Chess.Moves.Pawn - alias Chess.Moves.Rook alias Chess.Moves.Bishop + alias Chess.Moves.Knight + alias Chess.Moves.Rook alias Chess.Moves.Queen def available(board, {file, rank}) do @@ -17,7 +18,7 @@ defmodule Chess.Moves do %{"type" => "bishop"} -> Bishop.moves(board, {file, rank}) %{"type" => "knight"} -> - [] + Knight.moves(board, {file, rank}) %{"type" => "king"} -> [] %{"type" => "queen"} -> diff --git a/lib/chess/moves/knight.ex b/lib/chess/moves/knight.ex new file mode 100644 index 0000000..51ffe1d --- /dev/null +++ b/lib/chess/moves/knight.ex @@ -0,0 +1,15 @@ +defmodule Chess.Moves.Knight 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, 2}, {2, 1}, {-1, 2}, {-2, 1}, {1, -2}, {2, -1}, {-1, -2}, {-2, -1}] + end +end diff --git a/test/chess/moves/knight_test.exs b/test/chess/moves/knight_test.exs new file mode 100644 index 0000000..76e5309 --- /dev/null +++ b/test/chess/moves/knight_test.exs @@ -0,0 +1,29 @@ +defmodule Chess.Moves.KnightTest do + use Chess.DataCase + + alias Chess.Moves + + test "knights move in an L shape" do + board = %{"4,5" => %{"type" => "knight", "colour" => "white"}} + moves = Moves.available(board, {4, 5}) + + expected_moves = Enum.sort([ + {3, 7}, {5, 7}, {6, 6}, {6, 4}, {5, 3}, {3, 3}, {2, 4}, {2, 6}, + ]) + 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