mirror of
https://github.com/danbee/chess
synced 2025-03-04 08:39:06 +00:00
Knight moves
This commit is contained in:
parent
961920740e
commit
3a421ca213
@ -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"} ->
|
||||
|
||||
15
lib/chess/moves/knight.ex
Normal file
15
lib/chess/moves/knight.ex
Normal file
@ -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
|
||||
29
test/chess/moves/knight_test.exs
Normal file
29
test/chess/moves/knight_test.exs
Normal file
@ -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
|
||||
Loading…
Reference in New Issue
Block a user