mirror of
https://github.com/danbee/chess
synced 2025-03-04 08:39:06 +00:00
Add Rook moves
This commit is contained in:
parent
e608d9556d
commit
568c2cf7ff
@ -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
|
||||
|
||||
30
lib/chess/moves/rook.ex
Normal file
30
lib/chess/moves/rook.ex
Normal file
@ -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
|
||||
31
test/chess/moves/rook_test.exs
Normal file
31
test/chess/moves/rook_test.exs
Normal file
@ -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
|
||||
Loading…
Reference in New Issue
Block a user