summaryrefslogtreecommitdiff
path: root/lib/chessh/ssh/client/game/promotion.ex
blob: d9e9971e9bc7552192cba3f471193c9c108b11ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
defmodule Chessh.SSH.Client.Game.PromotionScreen do
  alias Chessh.Utils
  alias Chessh.SSH.Client.Game
  alias IO.ANSI

  defmodule State do
    defstruct game_pid: nil,
              client_pid: nil,
              game_state: nil
  end

  use Chessh.SSH.Client.Screen

  @promotion_screen Utils.clear_codes() ++
                      [
                        "Press the key associated to the piece you'd like to promote",
                        "  'q' - queen",
                        "  'r' - rook",
                        "  'n' - knight",
                        "  'b' - bishop"
                      ]

  def init([%State{} = state | _]) do
    {:ok, state}
  end

  def render(_, _, %State{client_pid: client_pid} = state) do
    rendered =
      Enum.flat_map(
        Enum.zip(0..(length(@promotion_screen) - 1), @promotion_screen),
        fn {i, promotion} ->
          [
            ANSI.cursor(i, 0),
            promotion
          ]
        end
      ) ++ [ANSI.home()]

    send(
      client_pid,
      {:send_to_ssh, rendered}
    )

    state
  end

  def input(
        _action,
        data,
        %State{client_pid: client_pid, game_pid: game_pid, game_state: %Game.State{} = game_state} =
          state
      ) do
    promotion = if Enum.member?(["q", "b", "n", "r"], data), do: data, else: nil

    if promotion do
      send(client_pid, {:go_back_one_screen, game_state})
      send(game_pid, {:promotion, promotion})
    end

    state
  end
end