diff --git a/lib/chess/moves.ex b/lib/chess/moves.ex index ae0ff6c..2594e15 100644 --- a/lib/chess/moves.ex +++ b/lib/chess/moves.ex @@ -2,6 +2,7 @@ defmodule Chess.Moves do @moduledoc false alias Chess.Moves.Pawn + alias Chess.Moves.Rook def available(board, {file, rank}) do piece = board["#{file},#{rank}"] @@ -9,6 +10,8 @@ defmodule Chess.Moves do case piece do %{"type" => "pawn"} -> Pawn.moves(board, {file, rank}) + %{"type" => "rook"} -> + Rook.moves(board, {file, rank}) end end end diff --git a/lib/chess/moves/rook.ex b/lib/chess/moves/rook.ex new file mode 100644 index 0000000..09e60fb --- /dev/null +++ b/lib/chess/moves/rook.ex @@ -0,0 +1,30 @@ +defmodule Chess.Moves.Rook do + @moduledoc false + + def moves(board, {file, rank}) do + moves_north(board, {file, rank}) ++ + moves_south(board, {file, rank}) ++ + moves_east(board, {file, rank}) ++ + moves_west(board, {file, rank}) + end + + defp moves_north(_board, {_file, 7}), do: [] + defp moves_north(board, {file, rank}) do + [{file, rank + 1} | moves_north(board, {file, rank + 1})] + end + + defp moves_south(_board, {_file, 0}), do: [] + defp moves_south(board, {file, rank}) do + [{file, rank - 1} | moves_south(board, {file, rank - 1})] + end + + defp moves_east(_board, {7, _rank}), do: [] + defp moves_east(board, {file, rank}) do + [{file + 1, rank} | moves_east(board, {file + 1, rank})] + end + + defp moves_west(_board, {0, _rank}), do: [] + defp moves_west(board, {file, rank}) do + [{file - 1, rank} | moves_west(board, {file - 1, rank})] + end +end diff --git a/test/chess/moves/rook_test.exs b/test/chess/moves/rook_test.exs new file mode 100644 index 0000000..da7d3ea --- /dev/null +++ b/test/chess/moves/rook_test.exs @@ -0,0 +1,31 @@ +defmodule Chess.Moves.RookTest do + use Chess.DataCase + + alias Chess.Moves.Rook + + test "rooks can move horizontally or vertically" do + board = %{"4,5" => %{"type" => "rook", "colour" => "white"}} + moves = Rook.moves(board, {4, 5}) + + expected_moves = Enum.sort([ + {4, 0}, {4, 1}, {4, 2}, {4, 3}, {4, 4}, {4, 6}, {4, 7}, + {0, 5}, {1, 5}, {2, 5}, {3, 5}, {5, 5}, {6, 5}, {7, 5}, + ]) + assert Enum.sort(moves) == expected_moves + end + + test "rook cannot move further than the edge" do + board = %{"0,0" => %{type: :rook, colour: :white}} + moves = Rook.moves(board, {0, 0}) + + expected_moves = Enum.sort([ + {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, + {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}, {7, 0}, + ]) + assert Enum.sort(moves) == expected_moves + end + + def board do + Chess.Board.default + end +end