1
0
mirror of https://github.com/danbee/chess synced 2025-03-04 08:39:06 +00:00

King moves

This commit is contained in:
Daniel Barber 2018-03-12 15:39:16 -04:00
parent 3a421ca213
commit 8c9d52a0a4
Signed by: danbarber
GPG Key ID: 931D8112E0103DD8
3 changed files with 46 additions and 1 deletions

View File

@ -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

15
lib/chess/moves/king.ex Normal file
View File

@ -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

View File

@ -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