Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions lib/chex/game/inspect.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
defimpl Inspect, for: Chex.Game do
@unicode_map %{
{:white, :pawn} => "♙",
{:white, :rook} => "♖",
{:white, :knight} => "♘",
{:white, :bishop} => "♗",
{:white, :queen} => "♕",
{:white, :king} => "♔",
{:black, :pawn} => "♟",
{:black, :rook} => "♜",
{:black, :knight} => "♞",
{:black, :bishop} => "♝",
{:black, :queen} => "♛",
{:black, :king} => "♚",
nil => " "
}

@ranks 8..1
@files [:a, :b, :c, :d, :e, :f, :g, :h]

@doc """
Output a string in the unicode notation shown below.

iex> Chex.Game.new
8 [♜][♞][♝][♛][♚][♝][♞][♜]
7 [♟][♟][♟][♟][♟][♟][♟][♟]
6 [ ][ ][ ][ ][ ][ ][ ][ ]
5 [ ][ ][ ][ ][ ][ ][ ][ ]
4 [ ][ ][ ][ ][ ][ ][ ][ ]
3 [ ][ ][ ][ ][ ][ ][ ][ ]
2 [♙][♙][♙][♙][♙][♙][♙][♙]
1 [♖][♘][♗][♕][♔][♗][♘][♖]
a b c d e f g h
"""
def inspect(game, opts) do
for rank <- @ranks, file <- @files do
piece =
case Map.get(game.board, {file, rank}) do
{material, color, _} -> {color, material}
_ -> nil
end

unicode = Map.get(@unicode_map, piece)
"[#{unicode}]"
end
|> Enum.chunk_every(8)
|> Enum.with_index()
|> Enum.map(fn {row, rank} -> ["#{8 - rank} " | row] |> Enum.join("") end)
|> Enum.concat([" a b c d e f g h"])
|> Enum.join("\n")
end
end
45 changes: 45 additions & 0 deletions test/chex/game/inspect_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
defmodule Chex.Game.InspectTest do
use ExUnit.Case, async: true

describe "inspect game" do
test "new game" do
expected =
"""
8 [♜][♞][♝][♛][♚][♝][♞][♜]
7 [♟][♟][♟][♟][♟][♟][♟][♟]
6 [ ][ ][ ][ ][ ][ ][ ][ ]
5 [ ][ ][ ][ ][ ][ ][ ][ ]
4 [ ][ ][ ][ ][ ][ ][ ][ ]
3 [ ][ ][ ][ ][ ][ ][ ][ ]
2 [♙][♙][♙][♙][♙][♙][♙][♙]
1 [♖][♘][♗][♕][♔][♗][♘][♖]
a b c d e f g h
"""
|> String.trim()

assert expected == inspect(Chex.new_game!())
end

test "promotion game" do
expected =
"""
8 [ ][ ][ ][ ][ ][ ][ ][ ]
7 [ ][ ][♚][ ][♙][ ][ ][ ]
6 [ ][ ][ ][ ][ ][ ][ ][ ]
5 [ ][ ][ ][ ][ ][ ][ ][ ]
4 [ ][ ][ ][ ][ ][ ][ ][ ]
3 [ ][ ][ ][ ][ ][ ][ ][ ]
2 [ ][ ][♔][ ][ ][ ][ ][ ]
1 [ ][ ][ ][ ][ ][ ][ ][ ]
a b c d e f g h
"""
|> String.trim()

{:ok, game} = Chex.Game.new("8/2k1P3/8/8/8/8/2K5/8 w - - 0 1")

IO.inspect(game)

assert expected == inspect(game)
end
end
end
3 changes: 1 addition & 2 deletions test/chex/game_test.exs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
defmodule Chex.GameTest do
use ExUnit.Case, async: true
import AssertValue

alias Chex.Game

describe "new/0" do
test "returns new game state" do
{:ok, game} = Game.new()

assert_value(
assert(
game == %Game{
active_color: :white,
board: %{
Expand Down