diff --git a/lib/chess/moves/king.ex b/lib/chess/moves/king.ex index 4f9ab9f..1121d95 100644 --- a/lib/chess/moves/king.ex +++ b/lib/chess/moves/king.ex @@ -1,12 +1,12 @@ 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) + alias Chess.Moves.Generator + + def moves(board, {file, rank}) do + board["#{file},#{rank}"] + |> Map.get("colour") + |> Generator.moves(board, {file, rank}, patterns()) end defp patterns do diff --git a/test/chess/moves/king_test.exs b/test/chess/moves/king_test.exs index 5cc8b2b..5a2cfe5 100644 --- a/test/chess/moves/king_test.exs +++ b/test/chess/moves/king_test.exs @@ -13,12 +13,25 @@ defmodule Chess.Moves.KingTest do 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"}} + test "kings cannot move beyond the edges of the board" do + board = %{"0,0" => %{"type" => "king", "colour" => "white"}} moves = Moves.available(board, {0, 0}) expected_moves = Enum.sort([ - {1, 2}, {2, 1} + {0, 1}, {1, 1}, {1, 0}, + ]) + assert Enum.sort(moves) == expected_moves + end + + test "kings are blocked by pieces of the same colour" do + board = %{ + "0,0" => %{"type" => "king", "colour" => "white"}, + "1,1" => %{"type" => "rook", "colour" => "white"}, + } + moves = Moves.available(board, {0, 0}) + + expected_moves = Enum.sort([ + {0, 1}, {1, 0}, ]) assert Enum.sort(moves) == expected_moves end