From bff9fd0a6ae8b1f034e4d20007b442957539e7ec Mon Sep 17 00:00:00 2001 From: Simponic Date: Wed, 4 Jan 2023 20:43:32 -0700 Subject: [PATCH 01/12] Well it's drawing *something* --- lib/chessh/ssh/screens/board.ex | 101 +++++++++++++++++++++++++++++++- priv/ascii_chars.json | 4 +- 2 files changed, 101 insertions(+), 4 deletions(-) diff --git a/lib/chessh/ssh/screens/board.ex b/lib/chessh/ssh/screens/board.ex index c95049f..9b18295 100644 --- a/lib/chessh/ssh/screens/board.ex +++ b/lib/chessh/ssh/screens/board.ex @@ -11,12 +11,109 @@ defmodule Chessh.SSH.Client.Board do use Chessh.SSH.Client.Screen + @chess_board_height 8 + @chess_board_width 8 + + def tileIsLight(row, col) do + rem(row, 2) == rem(col, 2) + end + + def piece_type(char) do + case String.capitalize(char) do + "P" -> "pawn" + "N" -> "knight" + "R" -> "rook" + "B" -> "bishop" + "K" -> "king" + "Q" -> "queen" + _ -> nil + end + end + + def make_board({tile_width, tile_height}) do + rows = + Enum.map(0..(@chess_board_height - 1), fn i -> + Enum.map(0..(@chess_board_width - 1), fn j -> + List.duplicate(if(tileIsLight(i, j), do: ' ', else: '#'), tile_width) + end) + end) + + Enum.flat_map(rows, fn row -> Enum.map(1..tile_height, fn _ -> row end) end) + end + + def make_board(fen, {tile_width, tile_height} = tile_dims) do + rows = + String.split(fen, " ") + |> List.first() + |> String.split("/") + + coordinate_to_piece = + Enum.zip(rows, 0..(length(rows) - 1)) + |> Enum.map(fn {row, rowI} -> + {@chess_board_height, pieces_per_row} = + Enum.reduce( + String.split(row, ""), + {0, %{}}, + fn char, {curr_column, data} -> + case Integer.parse(char) do + {skip, ""} -> + {curr_column + skip, data} + + _ -> + case piece_type(char) do + nil -> + {curr_column, data} + + type -> + {curr_column + 1, + Map.put( + data, + "#{rowI}, #{curr_column}", + @ascii_chars["pieces"][ + if(char != String.capitalize(char), do: "light", else: "dark") + ][type] + )} + end + end + end + ) + + pieces_per_row + end) + |> Enum.reduce(%{}, fn pieces_map_for_this_row, acc -> + Map.merge(acc, pieces_map_for_this_row) + end) + + board = make_board(tile_dims) + + Enum.zip_with([board, 1..length(board)], fn [row, rowI] -> + curr_y = div(rowI, tile_height) + + Enum.zip_with([row, 1..length(row)], fn [char, col] -> + curr_x = div(col, tile_width) + key = "#{rowI}, #{col}" + + if Map.has_key?(coordinate_to_piece, key) do + piece_char = + Map.fetch!(coordinate_to_piece, key) + |> Enum.at(rowI - curr_y * tile_height) + |> String.at(col - curr_x * tile_width) + + if piece_char == " ", do: String.Chars.to_string(char), else: piece_char + else + char + end + end) + |> Enum.join("") + end) + end + def render(%Client.State{} = _state) do - knight = @ascii_chars["pieces"]["white"]["knight"] + board = make_board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", {9, 5}) [ANSI.home()] ++ Enum.map( - Enum.zip(0..(length(knight) - 1), knight), + Enum.zip(0..(length(board) - 1), board), fn {i, line} -> [ANSI.cursor(i, 0), line] end diff --git a/priv/ascii_chars.json b/priv/ascii_chars.json index e50be22..58a7cb0 100644 --- a/priv/ascii_chars.json +++ b/priv/ascii_chars.json @@ -94,7 +94,7 @@ ] }, "pieces": { - "white": { + "light": { "rook": [ " ", " [`'`'] ", @@ -137,7 +137,7 @@ " " ] }, - "black": { + "dark": { "rook": [ " ", " [`'`'] ", From ce62dd6106f94473db919335cc49029421fde4ad Mon Sep 17 00:00:00 2001 From: Logan Hunt Date: Fri, 6 Jan 2023 17:02:56 -0700 Subject: [PATCH 02/12] Board drawing working --- lib/chessh/ssh/screens/board.ex | 37 ++++-- lib/chessh/ssh/screens/menu.ex | 2 +- priv/ascii_chars.json | 203 +++++--------------------------- 3 files changed, 57 insertions(+), 185 deletions(-) diff --git a/lib/chessh/ssh/screens/board.ex b/lib/chessh/ssh/screens/board.ex index 9b18295..3ce4fb6 100644 --- a/lib/chessh/ssh/screens/board.ex +++ b/lib/chessh/ssh/screens/board.ex @@ -34,8 +34,9 @@ defmodule Chessh.SSH.Client.Board do rows = Enum.map(0..(@chess_board_height - 1), fn i -> Enum.map(0..(@chess_board_width - 1), fn j -> - List.duplicate(if(tileIsLight(i, j), do: ' ', else: '#'), tile_width) + List.duplicate(if(tileIsLight(i, j), do: ' ', else: '▊'), tile_width) end) + |> Enum.join("") end) Enum.flat_map(rows, fn row -> Enum.map(1..tile_height, fn _ -> row end) end) @@ -70,7 +71,7 @@ defmodule Chessh.SSH.Client.Board do data, "#{rowI}, #{curr_column}", @ascii_chars["pieces"][ - if(char != String.capitalize(char), do: "light", else: "dark") + if(char != String.capitalize(char), do: "dark", else: "light") ][type] )} end @@ -86,20 +87,32 @@ defmodule Chessh.SSH.Client.Board do board = make_board(tile_dims) - Enum.zip_with([board, 1..length(board)], fn [row, rowI] -> - curr_y = div(rowI, tile_height) + Enum.zip_with([board, 0..(length(board) - 1)], fn [rowStr, row] -> + curr_y = div(row, tile_height) - Enum.zip_with([row, 1..length(row)], fn [char, col] -> + Enum.zip_with([String.graphemes(rowStr), 0..(String.length(rowStr) - 1)], fn [char, col] -> curr_x = div(col, tile_width) - key = "#{rowI}, #{col}" + key = "#{curr_y}, #{curr_x}" if Map.has_key?(coordinate_to_piece, key) do - piece_char = + piece_row = Map.fetch!(coordinate_to_piece, key) - |> Enum.at(rowI - curr_y * tile_height) - |> String.at(col - curr_x * tile_width) + |> Enum.at(row - curr_y * tile_height) - if piece_char == " ", do: String.Chars.to_string(char), else: piece_char + piece_row_len = String.length(piece_row) + centered_col = div(tile_width - piece_row_len, 2) + relative_to_tile_col = col - curr_x * tile_width + Logger.debug("#{piece_row_len}, #{centered_col}, #{relative_to_tile_col}") + + piece_char = + if relative_to_tile_col >= centered_col && + relative_to_tile_col <= tile_width - centered_col - 1, + do: String.at(piece_row, relative_to_tile_col - centered_col), + else: " " + + if piece_char == " ", + do: char, + else: piece_char else char end @@ -109,11 +122,11 @@ defmodule Chessh.SSH.Client.Board do end def render(%Client.State{} = _state) do - board = make_board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", {9, 5}) + board = make_board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", {7, 4}) [ANSI.home()] ++ Enum.map( - Enum.zip(0..(length(board) - 1), board), + Enum.zip(1..length(board), board), fn {i, line} -> [ANSI.cursor(i, 0), line] end diff --git a/lib/chessh/ssh/screens/menu.ex b/lib/chessh/ssh/screens/menu.ex index f89670f..9baa059 100644 --- a/lib/chessh/ssh/screens/menu.ex +++ b/lib/chessh/ssh/screens/menu.ex @@ -38,7 +38,7 @@ defmodule Chessh.SSH.Client.Menu do {y, x} = center_rect({logo_width, logo_height + length(text)}, {width, height}) Enum.flat_map( - Enum.zip(0..(length(text) - 1), text), + Enum.zip(1..length(text), text), fn {i, line} -> [ ANSI.cursor(y + i + dy, x + dx), diff --git a/priv/ascii_chars.json b/priv/ascii_chars.json index 58a7cb0..3f62794 100644 --- a/priv/ascii_chars.json +++ b/priv/ascii_chars.json @@ -1,184 +1,43 @@ { "letters": { - "a": [ - " ", - " /\\ ", - "/--\\" - ], - "b": [ - " __ ", - "|__)", - "|__)" - ], - "c": [ - " __ ", - "/ ", - "\\__ " - ], - "d": [ - " __ ", - "| \\", - "|__/" - ], - "e": [ - " __ ", - "|_ ", - "|__ " - ], - "f": [ - " __ ", - "|_ ", - "| " - ], - "g": [ - " __ ", - "/ _ ", - "\\__\\" - ], - "h": [ - "| |", - "|__|", - "| |" - ] + "a": [" ", " /\\ ", "/--\\"], + "b": [" __ ", "|__)", "|__)"], + "c": [" __ ", "/ ", "\\__ "], + "d": [" __ ", "| \\", "|__/"], + "e": [" __ ", "|_ ", "|__ "], + "f": [" __ ", "|_ ", "| "], + "g": [" __ ", "/ _ ", "\\__\\"], + "h": ["| |", "|__|", "| |"] }, "numbers": { - "0": [ - " _ ", - "| |", - "|_|" - ], - "1": [ - " ", - " /|", - " |" - ], - "2": [ - " _ ", - " )", - " /_" - ], - "3": [ - " _ ", - " _)", - " _)" - ], - "4": [ - " .", - " /|", - "'-|" - ], - "5": [ - " _ ", - "|_ ", - " _)" - ], - "6": [ - " ", - " / ", - "(_)" - ], - "7": [ - " __", - " /", - " / " - ], - "8": [ - " _ ", - "(_)", - "(_)" - ], - "9": [ - " _ ", - "(_)", - " )" - ] + "0": [" _ ", "| |", "|_|"], + "1": [" ", " /|", " |"], + "2": [" _ ", " )", " /_"], + "3": [" _ ", " _)", " _)"], + "4": [" .", " /|", "'-|"], + "5": [" _ ", "|_ ", " _)"], + "6": [" ", " / ", "(_)"], + "7": [" __", " /", " / "], + "8": [" _ ", "(_)", "(_)"], + "9": [" _ ", "(_)", " )"] }, + "pieces": { "light": { - "rook": [ - " ", - " [`'`'] ", - " | | ", - " |__| ", - " " - ], - "knight": [ - " _ _ ", - " \\` '/ ", - " (o o) ", - " \\ / \\", - " ^ " - ], - "queen": [ - " /\\+/\\ ", - " /(o o)\\ ", - " (_) ", - " " - ], - "king": [ - " ", - " |`+'| ", - " (o o) ", - " (_) ", - " " - ], - "bishop": [ - " ", - " |v| ", - " (0 o) ", - " (_) ", - " " - ], - "pawn": [ - " _ ", - " ( ) ", - " | | ", - " |_| ", - " " - ] + "rook": [" ", "L_|", " U ", "[.]"], + "knight": [" ", "/`)", " U ", "[.]"], + "bishop": [" . ", "(\\)", " U ", "[.]"], + "queen": [" . ", ").(", ").(", "[.]"], + "king": [" + ", ").(", ").(", "[.]"], + "pawn": [" ", " o ", " U ", "[.]"] }, "dark": { - "rook": [ - " ", - " [`'`'] ", - " |::| ", - " |::| ", - " " - ], - "knight": [ - " _ _ ", - " \\`.'/ ", - " (o:o) ", - " \\:/:\\", - " ^ " - ], - "queen": [ - " /\\+/\\ ", - " /(o:o)\\ ", - " (:) ", - " " - ], - "king": [ - " ", - " |`+'| ", - " (o:o) ", - " (:) ", - " " - ], - "bishop": [ - " ", - " |v| ", - " (o:o) ", - " (:) ", - " " - ], - "pawn": [ - " _ ", - " (:) ", - " |:| ", - " |_| ", - " " - ] + "rook": [" ", "L-|", " U ", "[#]"], + "knight": [" ", "/`)", " U ", "[#]"], + "bishop": [" . ", "(\\)", " U ", "[#]"], + "king": [" + ", ")#(", ")#(", "[#]"], + "queen": [" . ", ")#(", ")#(", "[#]"], + "pawn": [" ", " o ", " U ", "[#]"] } } } From 5b8dc2cb9800ed38ba1dc02fa5a135880a2c0bac Mon Sep 17 00:00:00 2001 From: Simponic Date: Fri, 6 Jan 2023 20:55:12 -0700 Subject: [PATCH 03/12] Checkpoint - board is drawn! --- lib/chessh/ssh/client.ex | 2 +- lib/chessh/ssh/screens/board.ex | 164 ++++++++++++++++++++------------ lib/chessh/ssh/tui.ex | 3 - priv/ascii_chars.json | 4 +- 4 files changed, 108 insertions(+), 65 deletions(-) diff --git a/lib/chessh/ssh/client.ex b/lib/chessh/ssh/client.ex index 4ed2fd1..fdd3875 100644 --- a/lib/chessh/ssh/client.ex +++ b/lib/chessh/ssh/client.ex @@ -12,7 +12,7 @@ defmodule Chessh.SSH.Client do ] @min_terminal_width 64 - @min_terminal_height 31 + @min_terminal_height 32 @max_terminal_width 255 @max_terminal_height 127 diff --git a/lib/chessh/ssh/screens/board.ex b/lib/chessh/ssh/screens/board.ex index 3ce4fb6..0aac50a 100644 --- a/lib/chessh/ssh/screens/board.ex +++ b/lib/chessh/ssh/screens/board.ex @@ -14,6 +14,9 @@ defmodule Chessh.SSH.Client.Board do @chess_board_height 8 @chess_board_width 8 + @dark_piece_color ANSI.magenta() + @light_piece_color ANSI.red() + def tileIsLight(row, col) do rem(row, 2) == rem(col, 2) end @@ -42,81 +45,124 @@ defmodule Chessh.SSH.Client.Board do Enum.flat_map(rows, fn row -> Enum.map(1..tile_height, fn _ -> row end) end) end - def make_board(fen, {tile_width, tile_height} = tile_dims) do + defp skip_cols_or_place_piece_reduce(char, {curr_column, data}, rowI) do + case Integer.parse(char) do + {skip, ""} -> + {curr_column + skip, data} + + _ -> + case piece_type(char) do + nil -> + {curr_column, data} + + type -> + shade = if(char != String.capitalize(char), do: "dark", else: "light") + + {curr_column + 1, + Map.put( + data, + "#{rowI}, #{curr_column}", + {shade, type} + )} + end + end + end + + defp make_coordinate_to_piece_art_map(fen) do rows = String.split(fen, " ") |> List.first() |> String.split("/") - coordinate_to_piece = - Enum.zip(rows, 0..(length(rows) - 1)) - |> Enum.map(fn {row, rowI} -> - {@chess_board_height, pieces_per_row} = - Enum.reduce( - String.split(row, ""), - {0, %{}}, - fn char, {curr_column, data} -> - case Integer.parse(char) do - {skip, ""} -> - {curr_column + skip, data} + Enum.zip(rows, 0..(length(rows) - 1)) + |> Enum.map(fn {row, rowI} -> + {@chess_board_height, pieces_per_row} = + Enum.reduce( + String.split(row, ""), + {0, %{}}, + &skip_cols_or_place_piece_reduce(&1, &2, rowI) + ) - _ -> - case piece_type(char) do - nil -> - {curr_column, data} - - type -> - {curr_column + 1, - Map.put( - data, - "#{rowI}, #{curr_column}", - @ascii_chars["pieces"][ - if(char != String.capitalize(char), do: "dark", else: "light") - ][type] - )} - end - end - end - ) - - pieces_per_row - end) - |> Enum.reduce(%{}, fn pieces_map_for_this_row, acc -> - Map.merge(acc, pieces_map_for_this_row) - end) + pieces_per_row + end) + |> Enum.reduce(%{}, fn pieces_map_for_this_row, acc -> + Map.merge(acc, pieces_map_for_this_row) + end) + end + def make_board(fen, {tile_width, tile_height} = tile_dims) do + coordinate_to_piece = make_coordinate_to_piece_art_map(fen) board = make_board(tile_dims) Enum.zip_with([board, 0..(length(board) - 1)], fn [rowStr, row] -> curr_y = div(row, tile_height) - Enum.zip_with([String.graphemes(rowStr), 0..(String.length(rowStr) - 1)], fn [char, col] -> - curr_x = div(col, tile_width) - key = "#{curr_y}, #{curr_x}" + %{row_chars: row_chars} = + Enum.reduce( + Enum.zip(String.graphemes(rowStr), 0..(String.length(rowStr) - 1)), + %{current_color: ANSI.black(), row_chars: []}, + fn {char, col}, %{current_color: current_color, row_chars: row_chars} = row_state -> + curr_x = div(col, tile_width) + key = "#{curr_y}, #{curr_x}" - if Map.has_key?(coordinate_to_piece, key) do - piece_row = - Map.fetch!(coordinate_to_piece, key) - |> Enum.at(row - curr_y * tile_height) + case Map.fetch(coordinate_to_piece, key) do + {:ok, {shade, type}} -> + piece = @ascii_chars["pieces"][shade][type] + piece_line = Enum.at(piece, row - curr_y * tile_height) - piece_row_len = String.length(piece_row) - centered_col = div(tile_width - piece_row_len, 2) - relative_to_tile_col = col - curr_x * tile_width - Logger.debug("#{piece_row_len}, #{centered_col}, #{relative_to_tile_col}") + piece_line_len = String.length(piece_line) + pad_left_right = div(tile_width - piece_line_len, 2) + relative_to_tile_col = col - curr_x * tile_width - piece_char = - if relative_to_tile_col >= centered_col && - relative_to_tile_col <= tile_width - centered_col - 1, - do: String.at(piece_row, relative_to_tile_col - centered_col), - else: " " + if relative_to_tile_col >= pad_left_right && + relative_to_tile_col < tile_width - pad_left_right do + piece_char = String.at(piece_line, relative_to_tile_col - pad_left_right) + new_char = if piece_char == " ", do: char, else: piece_char - if piece_char == " ", - do: char, - else: piece_char - else - char - end - end) + color = + if piece_char == " ", + do: ANSI.default_color(), + else: if(shade == "dark", do: @dark_piece_color, else: @light_piece_color) + + if color != current_color do + %{ + row_state + | current_color: color, + row_chars: row_chars ++ [color, new_char] + } + else + %{ + row_state + | current_color: current_color, + row_chars: row_chars ++ [new_char] + } + end + else + %{ + row_state + | current_color: ANSI.default_color(), + row_chars: row_chars ++ [ANSI.default_color(), char] + } + end + + _ -> + if ANSI.white() != current_color do + %{ + row_state + | current_color: ANSI.default_color(), + row_chars: row_chars ++ [ANSI.default_color(), char] + } + else + %{ + row_state + | row_chars: row_chars ++ [char] + } + end + end + end + ) + + row_chars |> Enum.join("") end) end diff --git a/lib/chessh/ssh/tui.ex b/lib/chessh/ssh/tui.ex index d76986f..5d43760 100644 --- a/lib/chessh/ssh/tui.ex +++ b/lib/chessh/ssh/tui.ex @@ -76,7 +76,6 @@ defmodule Chessh.SSH.Tui do {:send_data, data}, %{connection_ref: connection_ref, channel_id: channel_id} = state ) do - Logger.debug("Data was sent to TUI process #{inspect(data)}") :ssh_connection.send(connection_ref, channel_id, data) {:ok, state} end @@ -97,7 +96,6 @@ defmodule Chessh.SSH.Tui do {:ssh_cm, _connection_handler, {:data, _channel_id, _type, data}}, state ) do - Logger.debug("DATA #{inspect(data)}") send(state.client_pid, {:data, data}) {:ok, state} end @@ -132,7 +130,6 @@ defmodule Chessh.SSH.Tui do {:window_change, _channel_id, width, height, _pixwidth, _pixheight}}, %{client_pid: client_pid} = state ) do - Logger.debug("WINDOW CHANGE") send(client_pid, {:resize, {width, height}}) {:ok, diff --git a/priv/ascii_chars.json b/priv/ascii_chars.json index 3f62794..1be31f8 100644 --- a/priv/ascii_chars.json +++ b/priv/ascii_chars.json @@ -28,14 +28,14 @@ "knight": [" ", "/`)", " U ", "[.]"], "bishop": [" . ", "(\\)", " U ", "[.]"], "queen": [" . ", ").(", ").(", "[.]"], - "king": [" + ", ").(", ").(", "[.]"], + "king": [" + ", ").(", "|.|", "[.]"], "pawn": [" ", " o ", " U ", "[.]"] }, "dark": { "rook": [" ", "L-|", " U ", "[#]"], "knight": [" ", "/`)", " U ", "[#]"], "bishop": [" . ", "(\\)", " U ", "[#]"], - "king": [" + ", ")#(", ")#(", "[#]"], + "king": [" + ", ")#(", "|#|", "[#]"], "queen": [" . ", ")#(", ")#(", "[#]"], "pawn": [" ", " o ", " U ", "[#]"] } From 779c75dbe44516c0e1911cf8a56698a1508466b7 Mon Sep 17 00:00:00 2001 From: Simponic Date: Fri, 6 Jan 2023 22:29:01 -0700 Subject: [PATCH 04/12] Highlight a square --- lib/chessh/ssh/client.ex | 1 - lib/chessh/ssh/screens/board.ex | 110 ++++++++++++++++++++++++++------ lib/chessh/ssh/screens/menu.ex | 9 ++- 3 files changed, 94 insertions(+), 26 deletions(-) diff --git a/lib/chessh/ssh/client.ex b/lib/chessh/ssh/client.ex index fdd3875..290c9a7 100644 --- a/lib/chessh/ssh/client.ex +++ b/lib/chessh/ssh/client.ex @@ -73,7 +73,6 @@ defmodule Chessh.SSH.Client do new_state = module.handle_input(action, state) send(tui_pid, {:send_data, render(new_state)}) - {:noreply, new_state} end end diff --git a/lib/chessh/ssh/screens/board.ex b/lib/chessh/ssh/screens/board.ex index 0aac50a..09babad 100644 --- a/lib/chessh/ssh/screens/board.ex +++ b/lib/chessh/ssh/screens/board.ex @@ -2,17 +2,18 @@ defmodule Chessh.SSH.Client.Board do alias Chessh.SSH.Client alias IO.ANSI - require Logger - defmodule State do - defstruct cursor_x: 0, - cursor_y: 0 + defstruct cursor: %{x: 0, y: 0}, + highlighted: %{}, + move_from: nil end use Chessh.SSH.Client.Screen @chess_board_height 8 @chess_board_width 8 + @tile_width 7 + @tile_height 4 @dark_piece_color ANSI.magenta() @light_piece_color ANSI.red() @@ -35,9 +36,10 @@ defmodule Chessh.SSH.Client.Board do def make_board({tile_width, tile_height}) do rows = - Enum.map(0..(@chess_board_height - 1), fn i -> - Enum.map(0..(@chess_board_width - 1), fn j -> - List.duplicate(if(tileIsLight(i, j), do: ' ', else: '▊'), tile_width) + Enum.map(0..(@chess_board_height - 1), fn row -> + Enum.map(0..(@chess_board_width - 1), fn col -> + if(tileIsLight(row, col), do: ' ', else: '▊') + |> List.duplicate(tile_width) end) |> Enum.join("") end) @@ -90,7 +92,11 @@ defmodule Chessh.SSH.Client.Board do end) end - def make_board(fen, {tile_width, tile_height} = tile_dims) do + def draw_board( + fen, + {tile_width, tile_height} = tile_dims, + highlights + ) do coordinate_to_piece = make_coordinate_to_piece_art_map(fen) board = make_board(tile_dims) @@ -104,6 +110,18 @@ defmodule Chessh.SSH.Client.Board do fn {char, col}, %{current_color: current_color, row_chars: row_chars} = row_state -> curr_x = div(col, tile_width) key = "#{curr_y}, #{curr_x}" + relative_to_tile_col = col - curr_x * tile_width + + prefix = + if relative_to_tile_col == 0 do + case Map.fetch(highlights, {curr_y, curr_x}) do + {:ok, color} -> + color + + _ -> + ANSI.default_background() + end + end case Map.fetch(coordinate_to_piece, key) do {:ok, {shade, type}} -> @@ -112,7 +130,6 @@ defmodule Chessh.SSH.Client.Board do piece_line_len = String.length(piece_line) pad_left_right = div(tile_width - piece_line_len, 2) - relative_to_tile_col = col - curr_x * tile_width if relative_to_tile_col >= pad_left_right && relative_to_tile_col < tile_width - pad_left_right do @@ -128,20 +145,20 @@ defmodule Chessh.SSH.Client.Board do %{ row_state | current_color: color, - row_chars: row_chars ++ [color, new_char] + row_chars: row_chars ++ [prefix, color, new_char] } else %{ row_state | current_color: current_color, - row_chars: row_chars ++ [new_char] + row_chars: row_chars ++ [prefix, new_char] } end else %{ row_state | current_color: ANSI.default_color(), - row_chars: row_chars ++ [ANSI.default_color(), char] + row_chars: row_chars ++ [prefix, ANSI.default_color(), char] } end @@ -150,12 +167,12 @@ defmodule Chessh.SSH.Client.Board do %{ row_state | current_color: ANSI.default_color(), - row_chars: row_chars ++ [ANSI.default_color(), char] + row_chars: row_chars ++ [prefix, ANSI.default_color(), char] } else %{ row_state - | row_chars: row_chars ++ [char] + | row_chars: row_chars ++ [prefix, char] } end end @@ -167,8 +184,15 @@ defmodule Chessh.SSH.Client.Board do end) end - def render(%Client.State{} = _state) do - board = make_board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", {7, 4}) + def render(%Client.State{ + state_stack: [{_this_module, %State{highlighted: highlighted}} | _] + }) do + board = + draw_board( + "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", + {@tile_width, @tile_height}, + highlighted + ) [ANSI.home()] ++ Enum.map( @@ -179,9 +203,55 @@ defmodule Chessh.SSH.Client.Board do ) end - def handle_input(action, %Client.State{} = state) do - case action do - _ -> state - end + def handle_input( + action, + %Client.State{ + state_stack: [ + {this_module, + %State{ + move_from: move_from, + cursor: %{x: cursor_x, y: cursor_y} = cursor + } = screen_state} + | rest_stack + ] + } = state + ) do + new_cursor = + case action do + :left -> %{y: cursor_y, x: cursor_x - 1} + :right -> %{y: cursor_y, x: cursor_x + 1} + :down -> %{y: cursor_y + 1, x: cursor_x} + :up -> %{y: cursor_y - 1, x: cursor_x} + _ -> cursor + end + + {new_move_from, _move_to} = + if action == :return do + coords = {new_cursor.y, new_cursor.x} + + case move_from do + nil -> {coords, nil} + _ -> {nil, coords} + end + else + {move_from, nil} + end + + %Client.State{ + state + | state_stack: [ + {this_module, + %State{ + screen_state + | cursor: new_cursor, + move_from: new_move_from, + highlighted: %{ + new_move_from => ANSI.green_background(), + {new_cursor.y, new_cursor.x} => ANSI.green_background() + } + }} + | rest_stack + ] + } end end diff --git a/lib/chessh/ssh/screens/menu.ex b/lib/chessh/ssh/screens/menu.ex index 9baa059..d9df1b7 100644 --- a/lib/chessh/ssh/screens/menu.ex +++ b/lib/chessh/ssh/screens/menu.ex @@ -23,15 +23,14 @@ defmodule Chessh.SSH.Client.Menu do MMMMMMMMMMM MMMMMMMMMMM MMMMMMMMMMMM" @options [ - {"Option 1", {Chessh.SSH.Client.Board, %{}}}, - {"Option 2", {Chessh.SSH.Client.Board, %{}}}, - {"Option 3", {Chessh.SSH.Client.Board, %{}}} + {"Option 1", {Chessh.SSH.Client.Board, %Chessh.SSH.Client.Board.State{}}}, + {"Option 2", {Chessh.SSH.Client.Board, %Chessh.SSH.Client.Board.State{}}} ] def render(%Client.State{ width: width, height: height, - state_stack: [{_this_module, %State{selected: selected, y: dy, x: dx}} | _tail] + state_stack: [{_this_module, %State{selected: selected, y: dy, x: dx}} | _] }) do text = String.split(@logo, "\n") {logo_width, logo_height} = Utils.text_dim(@logo) @@ -57,7 +56,7 @@ defmodule Chessh.SSH.Client.Menu do ) ++ [ANSI.home()] end - def wrap_around(index, delta, length) do + defp wrap_around(index, delta, length) do calc = index + delta if(calc < 0, do: length, else: 0) + rem(calc, length) end From 2ce03d4796ad54f332c70ff88f0a9f3a164bbc4a Mon Sep 17 00:00:00 2001 From: Simponic Date: Wed, 11 Jan 2023 09:54:05 -0700 Subject: [PATCH 05/12] Checkpoint\? --- TODO.md | 1 + lib/chessh/ssh/client/board.ex | 276 ++++++++++++++++++++++++++ lib/chessh/ssh/client/board/server.ex | 19 ++ lib/chessh/ssh/{ => client}/client.ex | 58 +++--- lib/chessh/ssh/client/menu.ex | 100 ++++++++++ lib/chessh/ssh/client/screen.ex | 31 +++ lib/chessh/ssh/screens/board.ex | 257 ------------------------ lib/chessh/ssh/screens/menu.ex | 104 ---------- lib/chessh/ssh/screens/screen.ex | 22 -- mix.exs | 2 +- mix.lock | 2 + 11 files changed, 456 insertions(+), 416 deletions(-) create mode 100644 TODO.md create mode 100644 lib/chessh/ssh/client/board.ex create mode 100644 lib/chessh/ssh/client/board/server.ex rename lib/chessh/ssh/{ => client}/client.ex (62%) create mode 100644 lib/chessh/ssh/client/menu.ex create mode 100644 lib/chessh/ssh/client/screen.ex delete mode 100644 lib/chessh/ssh/screens/board.ex delete mode 100644 lib/chessh/ssh/screens/menu.ex delete mode 100644 lib/chessh/ssh/screens/screen.ex diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..5f54fe5 --- /dev/null +++ b/TODO.md @@ -0,0 +1 @@ +Change the menu and board to be genserverse, board subscribes to game, diff --git a/lib/chessh/ssh/client/board.ex b/lib/chessh/ssh/client/board.ex new file mode 100644 index 0000000..b192cfe --- /dev/null +++ b/lib/chessh/ssh/client/board.ex @@ -0,0 +1,276 @@ +# defmodule Chessh.SSH.Client.Board do +# alias Chessh.SSH.Client +# alias IO.ANSI +# +# require Logger +# +# defmodule State do +# defstruct cursor: %{x: 0, y: 0}, +# highlighted: %{}, +# move_from: nil +# end +# +# use GenServer +# use Chessh.SSH.Client.Screen +# +# @chess_board_height 8 +# @chess_board_width 8 +# @tile_width 7 +# @tile_height 4 +# +# @dark_piece_color ANSI.magenta() +# @light_piece_color ANSI.red() +# +# def tileIsLight(row, col) do +# rem(row, 2) == rem(col, 2) +# end +# +# def piece_type(char) do +# case String.capitalize(char) do +# "P" -> "pawn" +# "N" -> "knight" +# "R" -> "rook" +# "B" -> "bishop" +# "K" -> "king" +# "Q" -> "queen" +# _ -> nil +# end +# end +# +# def make_board({tile_width, tile_height}) do +# rows = +# Enum.map(0..(@chess_board_height - 1), fn row -> +# Enum.map(0..(@chess_board_width - 1), fn col -> +# if(tileIsLight(row, col), do: ' ', else: '▊') +# |> List.duplicate(tile_width) +# end) +# |> Enum.join("") +# end) +# +# Enum.flat_map(rows, fn row -> Enum.map(1..tile_height, fn _ -> row end) end) +# end +# +# defp skip_cols_or_place_piece_reduce(char, {curr_column, data}, rowI) do +# case Integer.parse(char) do +# {skip, ""} -> +# {curr_column + skip, data} +# +# _ -> +# case piece_type(char) do +# nil -> +# {curr_column, data} +# +# type -> +# shade = if(char != String.capitalize(char), do: "light", else: "dark") +# +# {curr_column + 1, +# Map.put( +# data, +# "#{rowI}, #{curr_column}", +# {shade, type} +# )} +# end +# end +# end +# +# defp make_coordinate_to_piece_art_map(fen) do +# rows = +# String.split(fen, " ") +# |> List.first() +# |> String.split("/") +# +# Enum.zip(rows, 0..(length(rows) - 1)) +# |> Enum.map(fn {row, rowI} -> +# {@chess_board_height, pieces_per_row} = +# Enum.reduce( +# String.split(row, ""), +# {0, %{}}, +# &skip_cols_or_place_piece_reduce(&1, &2, rowI) +# ) +# +# pieces_per_row +# end) +# |> Enum.reduce(%{}, fn pieces_map_for_this_row, acc -> +# Map.merge(acc, pieces_map_for_this_row) +# end) +# end +# +# def draw_board( +# fen, +# {tile_width, tile_height} = tile_dims, +# highlights +# ) do +# coordinate_to_piece = make_coordinate_to_piece_art_map(fen) +# board = make_board(tile_dims) +# +# Enum.zip_with([board, 0..(length(board) - 1)], fn [rowStr, row] -> +# curr_y = div(row, tile_height) +# +# %{row_chars: row_chars} = +# Enum.reduce( +# Enum.zip(String.graphemes(rowStr), 0..(String.length(rowStr) - 1)), +# %{current_color: ANSI.black(), row_chars: []}, +# fn {char, col}, %{current_color: current_color, row_chars: row_chars} = row_state -> +# curr_x = div(col, tile_width) +# key = "#{curr_y}, #{curr_x}" +# relative_to_tile_col = col - curr_x * tile_width +# +# prefix = +# if relative_to_tile_col == 0 do +# case Map.fetch(highlights, {curr_y, curr_x}) do +# {:ok, color} -> +# color +# +# _ -> +# ANSI.default_background() +# end +# end +# +# case Map.fetch(coordinate_to_piece, key) do +# {:ok, {shade, type}} -> +# piece = @ascii_chars["pieces"][shade][type] +# piece_line = Enum.at(piece, row - curr_y * tile_height) +# +# piece_line_len = String.length(piece_line) +# pad_left_right = div(tile_width - piece_line_len, 2) +# +# if relative_to_tile_col >= pad_left_right && +# relative_to_tile_col < tile_width - pad_left_right do +# piece_char = String.at(piece_line, relative_to_tile_col - pad_left_right) +# new_char = if piece_char == " ", do: char, else: piece_char +# +# color = +# if piece_char == " ", +# do: ANSI.default_color(), +# else: if(shade == "dark", do: @dark_piece_color, else: @light_piece_color) +# +# if color != current_color do +# %{ +# row_state +# | current_color: color, +# row_chars: row_chars ++ [prefix, color, new_char] +# } +# else +# %{ +# row_state +# | current_color: current_color, +# row_chars: row_chars ++ [prefix, new_char] +# } +# end +# else +# %{ +# row_state +# | current_color: ANSI.default_color(), +# row_chars: row_chars ++ [prefix, ANSI.default_color(), char] +# } +# end +# +# _ -> +# if ANSI.white() != current_color do +# %{ +# row_state +# | current_color: ANSI.default_color(), +# row_chars: row_chars ++ [prefix, ANSI.default_color(), char] +# } +# else +# %{ +# row_state +# | row_chars: row_chars ++ [prefix, char] +# } +# end +# end +# end +# ) +# +# row_chars +# |> Enum.join("") +# end) +# end +# +# def render(%Client.State{ +# state_stack: [{_this_module, %State{highlighted: highlighted}} | _] +# }) do +# board = +# draw_board( +# "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", +# {@tile_width, @tile_height}, +# highlighted +# ) +# +# [ANSI.home()] ++ +# Enum.map( +# Enum.zip(1..length(board), board), +# fn {i, line} -> +# [ANSI.cursor(i, 0), line] +# end +# ) +# end +# +# def handle_input( +# action, +# %Client.State{ +# binbo_pid: binbo_pid, +# state_stack: [ +# {this_module, +# %State{ +# move_from: move_from, +# cursor: %{x: cursor_x, y: cursor_y} = cursor +# } = screen_state} +# | rest_stack +# ] +# } = state +# ) do +# new_cursor = +# case action do +# :left -> %{y: cursor_y, x: cursor_x - 1} +# :right -> %{y: cursor_y, x: cursor_x + 1} +# :down -> %{y: cursor_y + 1, x: cursor_x} +# :up -> %{y: cursor_y - 1, x: cursor_x} +# _ -> cursor +# end +# +# {new_move_from, move_to} = +# if action == :return do +# coords = {new_cursor.y, new_cursor.x} +# +# case move_from do +# nil -> {coords, nil} +# _ -> {nil, coords} +# end +# else +# {move_from, nil} +# end +# +# if move_from && move_to do +# # Logger.debug(inspect(attempt_move(%Chess.Game{}, move_from, move_to))) +# attempted_move = "#{to_chess_coord(move_from)}#{to_chess_coord(move_to)}" +# +# case :binbo.move(binbo_pid, attempted_move) do +# # state.game_id}, {:new_move, :attempted_move}) +# {:ok, _} -> :syn.publish(:games, {:game, "asdf"}, {:new_move, attempted_move}) +# end +# end +# +# %Client.State{ +# state +# | state_stack: [ +# {this_module, +# %State{ +# screen_state +# | cursor: new_cursor, +# move_from: new_move_from, +# highlighted: %{ +# new_move_from => ANSI.green_background(), +# {new_cursor.y, new_cursor.x} => ANSI.green_background() +# } +# }} +# | rest_stack +# ] +# } +# end +# +# defp to_chess_coord({y, x}) +# when x >= 0 and x < @chess_board_width and y >= 0 and y < @chess_board_height do +# "#{List.to_string([?a + x])}#{y + 1}" +# end +# end diff --git a/lib/chessh/ssh/client/board/server.ex b/lib/chessh/ssh/client/board/server.ex new file mode 100644 index 0000000..2e480e7 --- /dev/null +++ b/lib/chessh/ssh/client/board/server.ex @@ -0,0 +1,19 @@ +# defmodule Chessh.SSH.Client.Board.Server do +# use GenServer +# +# defmodule State do +# defstruct game_id: nil, +# binbo_pid: nil +# end +# +# def init([%State{game_id: game_id} = state]) do +# {:ok, binbo_pid} = GenServer.start_link(:binbo, []) +# +# :syn.join(:games, {:game, game_id}) +# {:ok, state} +# end +# +# def handle_cast({:new_move, attempted_move}, %State{game_id: game_id} = state) do +# {:no_reply, state} +# end +# end diff --git a/lib/chessh/ssh/client.ex b/lib/chessh/ssh/client/client.ex similarity index 62% rename from lib/chessh/ssh/client.ex rename to lib/chessh/ssh/client/client.ex index 290c9a7..a5f7bec 100644 --- a/lib/chessh/ssh/client.ex +++ b/lib/chessh/ssh/client/client.ex @@ -11,8 +11,6 @@ defmodule Chessh.SSH.Client do ANSI.home() ] - @min_terminal_width 64 - @min_terminal_height 32 @max_terminal_width 255 @max_terminal_height 127 @@ -25,14 +23,17 @@ defmodule Chessh.SSH.Client do width: 0, height: 0, player_session: nil, - buffer: [], - state_stack: [{Menu, %Menu.State{}}] + screen_processes: [] end @impl true def init([%State{tui_pid: tui_pid} = state]) do - send(tui_pid, {:send_data, render(state)}) - {:ok, state} + {:ok, screen_pid} = + GenServer.start_link(Chessh.SSH.Client.Menu, [ + %Chessh.SSH.Client.Menu.State{tui_pid: tui_pid} + ]) + + {:ok, %{state | screen_processes: [screen_pid]}} end @impl true @@ -63,25 +64,36 @@ defmodule Chessh.SSH.Client do def handle( {:data, data}, - %State{tui_pid: tui_pid, state_stack: [{module, _screen_state} | _tail]} = state + %State{width: width, height: height, screen_processes: [screen_pid | _]} = state ) do action = keymap(data) if action == :quit do {:stop, :normal, state} else - new_state = module.handle_input(action, state) - - send(tui_pid, {:send_data, render(new_state)}) - {:noreply, new_state} + send(screen_pid, {:input, width, height, action}) + {:noreply, state} end end - def handle({:resize, {width, height}}, %State{tui_pid: tui_pid} = state) do + # def handle( + # {:refresh, }, + # %State{screen_processes: [screen_pid | _] = screen_processes, width: width, height: height} = state + # ) do + # send(screen_pid, {:render, tui_pid, width, height}) + # {:noreply, state} + # end + + def handle( + {:resize, {width, height}}, + %State{tui_pid: tui_pid, screen_processes: [screen_pid | _]} = state + ) do new_state = %State{state | width: width, height: height} - if height <= @max_terminal_height || width <= @max_terminal_width do - send(tui_pid, {:send_data, render(new_state)}) + if height <= @max_terminal_height && width <= @max_terminal_width do + send(screen_pid, {:render, width, height}) + else + send(tui_pid, {:send_data, @terminal_bad_dim_msg}) end {:noreply, new_state} @@ -101,22 +113,4 @@ defmodule Chessh.SSH.Client do x -> x end end - - def terminal_size_allowed(width, height) do - Enum.member?(@min_terminal_width..@max_terminal_width, width) && - Enum.member?(@min_terminal_height..@max_terminal_height, height) - end - - def render( - %State{width: width, height: height, state_stack: [{module, _screen_state} | _]} = state - ) do - if terminal_size_allowed(width, height) do - [ - @clear_codes ++ - module.render(state) - ] - else - @terminal_bad_dim_msg - end - end end diff --git a/lib/chessh/ssh/client/menu.ex b/lib/chessh/ssh/client/menu.ex new file mode 100644 index 0000000..a69ad88 --- /dev/null +++ b/lib/chessh/ssh/client/menu.ex @@ -0,0 +1,100 @@ +defmodule Chessh.SSH.Client.Menu do + alias Chessh.Utils + alias IO.ANSI + + require Logger + + defmodule State do + defstruct dy: 0, + dx: 0, + tui_pid: nil, + selected: 0 + end + + use Chessh.SSH.Client.Screen + + def init([%State{} = state | _]) do + {:ok, state} + end + + @logo " Simponic's + dP MP\"\"\"\"\"\"`MM MP\"\"\"\"\"\"`MM M\"\"MMMMM\"\"MM + 88 M mmmmm..M M mmmmm..M M MMMMM MM +.d8888b. 88d888b. .d8888b. M. `YM M. `YM M `M +88' `\"\" 88' `88 88ooood8 MMMMMMM. M MMMMMMM. M M MMMMM MM +88. ... 88 88 88. ... M. .MMM' M M. .MMM' M M MMMMM MM +`88888P' dP dP `88888P' Mb. .dM Mb. .dM M MMMMM MM + MMMMMMMMMMM MMMMMMMMMMM MMMMMMMMMMMM" + + # @options [ + # {"Option 1", {Chessh.SSH.Client.Board, [%Chessh.SSH.Client.Board.State{}]}}, + # {"Option 2", {Chessh.SSH.Client.Board, [%Chessh.SSH.Client.Board.State{}]}} + # ] + @options [ + {"Option 1", {}}, + {"Option 2", {}}, + {"Option 3", {}} + ] + + def handle_info({:render, width, height}, %State{} = state) do + render(width, height, state) + {:noreply, state} + end + + def handle_info({:input, width, height, action}, %State{selected: selected} = state) do + new_state = + case(action) do + :up -> + %State{ + state + | selected: wrap_around(selected, -1, length(@options)) + } + + :down -> + %State{state | selected: wrap_around(selected, 1, length(@options))} + + # :return -> + # {_, new_state} = Enum.at(@options, selected) + # new_state + + _ -> + state + end + + render(width, height, new_state) + {:noreply, new_state} + end + + def render(width, height, %State{tui_pid: tui_pid, dy: dy, dx: dx, selected: selected}) do + text = String.split(@logo, "\n") + {logo_width, logo_height} = Utils.text_dim(@logo) + {y, x} = center_rect({logo_width, logo_height + length(text)}, {width, height}) + + rendered = + Enum.flat_map( + Enum.zip(1..length(text), text), + fn {i, line} -> + [ + ANSI.cursor(y + i + dy, x + dx), + line + ] + end + ) ++ + Enum.flat_map( + Enum.zip(0..(length(@options) - 1), @options), + fn {i, {option, _}} -> + [ + ANSI.cursor(y + length(text) + i + dy, x + dx), + if(i == selected, do: ANSI.format([:light_cyan, "* #{option}"]), else: option) + ] + end + ) ++ [ANSI.home()] + + send(tui_pid, {:send_data, rendered}) + end + + defp wrap_around(index, delta, length) do + calc = index + delta + if(calc < 0, do: length, else: 0) + rem(calc, length) + end +end diff --git a/lib/chessh/ssh/client/screen.ex b/lib/chessh/ssh/client/screen.ex new file mode 100644 index 0000000..2dd9f9c --- /dev/null +++ b/lib/chessh/ssh/client/screen.ex @@ -0,0 +1,31 @@ +defmodule Chessh.SSH.Client.Screen do + @callback handle_info( + {:render, width :: integer(), height :: integer()}, + state :: any() + ) :: + {:noreply, any()} + @callback handle_info({:input, width :: integer(), height :: integer(), action :: any()}) :: + {:noreply, any()} + + # @callback render(state :: Chessh.SSH.Client.State.t() | any()) :: any() + # @callback handle_input(action :: any(), state :: Chessh.SSH.Client.State.t()) :: + # Chessh.SSH.Client.State.t() + + defmacro __using__(_) do + quote do + @behaviour Chessh.SSH.Client.Screen + use GenServer + + @ascii_chars Application.compile_env!(:chessh, :ascii_chars_json_file) + |> File.read!() + |> Jason.decode!() + + def center_rect({rect_width, rect_height}, {parent_width, parent_height}) do + { + div(parent_height - rect_height, 2), + div(parent_width - rect_width, 2) + } + end + end + end +end diff --git a/lib/chessh/ssh/screens/board.ex b/lib/chessh/ssh/screens/board.ex deleted file mode 100644 index 09babad..0000000 --- a/lib/chessh/ssh/screens/board.ex +++ /dev/null @@ -1,257 +0,0 @@ -defmodule Chessh.SSH.Client.Board do - alias Chessh.SSH.Client - alias IO.ANSI - - defmodule State do - defstruct cursor: %{x: 0, y: 0}, - highlighted: %{}, - move_from: nil - end - - use Chessh.SSH.Client.Screen - - @chess_board_height 8 - @chess_board_width 8 - @tile_width 7 - @tile_height 4 - - @dark_piece_color ANSI.magenta() - @light_piece_color ANSI.red() - - def tileIsLight(row, col) do - rem(row, 2) == rem(col, 2) - end - - def piece_type(char) do - case String.capitalize(char) do - "P" -> "pawn" - "N" -> "knight" - "R" -> "rook" - "B" -> "bishop" - "K" -> "king" - "Q" -> "queen" - _ -> nil - end - end - - def make_board({tile_width, tile_height}) do - rows = - Enum.map(0..(@chess_board_height - 1), fn row -> - Enum.map(0..(@chess_board_width - 1), fn col -> - if(tileIsLight(row, col), do: ' ', else: '▊') - |> List.duplicate(tile_width) - end) - |> Enum.join("") - end) - - Enum.flat_map(rows, fn row -> Enum.map(1..tile_height, fn _ -> row end) end) - end - - defp skip_cols_or_place_piece_reduce(char, {curr_column, data}, rowI) do - case Integer.parse(char) do - {skip, ""} -> - {curr_column + skip, data} - - _ -> - case piece_type(char) do - nil -> - {curr_column, data} - - type -> - shade = if(char != String.capitalize(char), do: "dark", else: "light") - - {curr_column + 1, - Map.put( - data, - "#{rowI}, #{curr_column}", - {shade, type} - )} - end - end - end - - defp make_coordinate_to_piece_art_map(fen) do - rows = - String.split(fen, " ") - |> List.first() - |> String.split("/") - - Enum.zip(rows, 0..(length(rows) - 1)) - |> Enum.map(fn {row, rowI} -> - {@chess_board_height, pieces_per_row} = - Enum.reduce( - String.split(row, ""), - {0, %{}}, - &skip_cols_or_place_piece_reduce(&1, &2, rowI) - ) - - pieces_per_row - end) - |> Enum.reduce(%{}, fn pieces_map_for_this_row, acc -> - Map.merge(acc, pieces_map_for_this_row) - end) - end - - def draw_board( - fen, - {tile_width, tile_height} = tile_dims, - highlights - ) do - coordinate_to_piece = make_coordinate_to_piece_art_map(fen) - board = make_board(tile_dims) - - Enum.zip_with([board, 0..(length(board) - 1)], fn [rowStr, row] -> - curr_y = div(row, tile_height) - - %{row_chars: row_chars} = - Enum.reduce( - Enum.zip(String.graphemes(rowStr), 0..(String.length(rowStr) - 1)), - %{current_color: ANSI.black(), row_chars: []}, - fn {char, col}, %{current_color: current_color, row_chars: row_chars} = row_state -> - curr_x = div(col, tile_width) - key = "#{curr_y}, #{curr_x}" - relative_to_tile_col = col - curr_x * tile_width - - prefix = - if relative_to_tile_col == 0 do - case Map.fetch(highlights, {curr_y, curr_x}) do - {:ok, color} -> - color - - _ -> - ANSI.default_background() - end - end - - case Map.fetch(coordinate_to_piece, key) do - {:ok, {shade, type}} -> - piece = @ascii_chars["pieces"][shade][type] - piece_line = Enum.at(piece, row - curr_y * tile_height) - - piece_line_len = String.length(piece_line) - pad_left_right = div(tile_width - piece_line_len, 2) - - if relative_to_tile_col >= pad_left_right && - relative_to_tile_col < tile_width - pad_left_right do - piece_char = String.at(piece_line, relative_to_tile_col - pad_left_right) - new_char = if piece_char == " ", do: char, else: piece_char - - color = - if piece_char == " ", - do: ANSI.default_color(), - else: if(shade == "dark", do: @dark_piece_color, else: @light_piece_color) - - if color != current_color do - %{ - row_state - | current_color: color, - row_chars: row_chars ++ [prefix, color, new_char] - } - else - %{ - row_state - | current_color: current_color, - row_chars: row_chars ++ [prefix, new_char] - } - end - else - %{ - row_state - | current_color: ANSI.default_color(), - row_chars: row_chars ++ [prefix, ANSI.default_color(), char] - } - end - - _ -> - if ANSI.white() != current_color do - %{ - row_state - | current_color: ANSI.default_color(), - row_chars: row_chars ++ [prefix, ANSI.default_color(), char] - } - else - %{ - row_state - | row_chars: row_chars ++ [prefix, char] - } - end - end - end - ) - - row_chars - |> Enum.join("") - end) - end - - def render(%Client.State{ - state_stack: [{_this_module, %State{highlighted: highlighted}} | _] - }) do - board = - draw_board( - "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", - {@tile_width, @tile_height}, - highlighted - ) - - [ANSI.home()] ++ - Enum.map( - Enum.zip(1..length(board), board), - fn {i, line} -> - [ANSI.cursor(i, 0), line] - end - ) - end - - def handle_input( - action, - %Client.State{ - state_stack: [ - {this_module, - %State{ - move_from: move_from, - cursor: %{x: cursor_x, y: cursor_y} = cursor - } = screen_state} - | rest_stack - ] - } = state - ) do - new_cursor = - case action do - :left -> %{y: cursor_y, x: cursor_x - 1} - :right -> %{y: cursor_y, x: cursor_x + 1} - :down -> %{y: cursor_y + 1, x: cursor_x} - :up -> %{y: cursor_y - 1, x: cursor_x} - _ -> cursor - end - - {new_move_from, _move_to} = - if action == :return do - coords = {new_cursor.y, new_cursor.x} - - case move_from do - nil -> {coords, nil} - _ -> {nil, coords} - end - else - {move_from, nil} - end - - %Client.State{ - state - | state_stack: [ - {this_module, - %State{ - screen_state - | cursor: new_cursor, - move_from: new_move_from, - highlighted: %{ - new_move_from => ANSI.green_background(), - {new_cursor.y, new_cursor.x} => ANSI.green_background() - } - }} - | rest_stack - ] - } - end -end diff --git a/lib/chessh/ssh/screens/menu.ex b/lib/chessh/ssh/screens/menu.ex deleted file mode 100644 index d9df1b7..0000000 --- a/lib/chessh/ssh/screens/menu.ex +++ /dev/null @@ -1,104 +0,0 @@ -defmodule Chessh.SSH.Client.Menu do - alias Chessh.SSH.Client - alias Chessh.Utils - alias IO.ANSI - - require Logger - - defmodule State do - defstruct y: 0, - x: 0, - selected: 0 - end - - use Chessh.SSH.Client.Screen - - @logo " Simponic's - dP MP\"\"\"\"\"\"`MM MP\"\"\"\"\"\"`MM M\"\"MMMMM\"\"MM - 88 M mmmmm..M M mmmmm..M M MMMMM MM -.d8888b. 88d888b. .d8888b. M. `YM M. `YM M `M -88' `\"\" 88' `88 88ooood8 MMMMMMM. M MMMMMMM. M M MMMMM MM -88. ... 88 88 88. ... M. .MMM' M M. .MMM' M M MMMMM MM -`88888P' dP dP `88888P' Mb. .dM Mb. .dM M MMMMM MM - MMMMMMMMMMM MMMMMMMMMMM MMMMMMMMMMMM" - - @options [ - {"Option 1", {Chessh.SSH.Client.Board, %Chessh.SSH.Client.Board.State{}}}, - {"Option 2", {Chessh.SSH.Client.Board, %Chessh.SSH.Client.Board.State{}}} - ] - - def render(%Client.State{ - width: width, - height: height, - state_stack: [{_this_module, %State{selected: selected, y: dy, x: dx}} | _] - }) do - text = String.split(@logo, "\n") - {logo_width, logo_height} = Utils.text_dim(@logo) - {y, x} = center_rect({logo_width, logo_height + length(text)}, {width, height}) - - Enum.flat_map( - Enum.zip(1..length(text), text), - fn {i, line} -> - [ - ANSI.cursor(y + i + dy, x + dx), - line - ] - end - ) ++ - Enum.flat_map( - Enum.zip(0..(length(@options) - 1), @options), - fn {i, {option, _}} -> - [ - ANSI.cursor(y + length(text) + i + dy, x + dx), - if(i == selected, do: ANSI.format([:light_cyan, "* #{option}"]), else: option) - ] - end - ) ++ [ANSI.home()] - end - - defp wrap_around(index, delta, length) do - calc = index + delta - if(calc < 0, do: length, else: 0) + rem(calc, length) - end - - def handle_input( - data, - %Client.State{ - state_stack: - [{this_module, %State{selected: selected} = screen_state} | tail] = state_stack - } = state - ) do - case(data) do - :up -> - %Client.State{ - state - | state_stack: [ - {this_module, - %State{screen_state | selected: wrap_around(selected, -1, length(@options))}} - | tail - ] - } - - :down -> - %Client.State{ - state - | state_stack: [ - {this_module, - %State{screen_state | selected: wrap_around(selected, 1, length(@options))}} - | tail - ] - } - - :return -> - {_, new_state} = Enum.at(@options, selected) - - %Client.State{ - state - | state_stack: [new_state] ++ state_stack - } - - _ -> - state - end - end -end diff --git a/lib/chessh/ssh/screens/screen.ex b/lib/chessh/ssh/screens/screen.ex deleted file mode 100644 index 3d9e9ec..0000000 --- a/lib/chessh/ssh/screens/screen.ex +++ /dev/null @@ -1,22 +0,0 @@ -defmodule Chessh.SSH.Client.Screen do - @callback render(state :: Chessh.SSH.Client.State.t() | any()) :: any() - @callback handle_input(action :: any(), state :: Chessh.SSH.Client.State.t()) :: - Chessh.SSH.Client.State.t() - - defmacro __using__(_) do - quote do - @behaviour Chessh.SSH.Client.Screen - - @ascii_chars Application.compile_env!(:chessh, :ascii_chars_json_file) - |> File.read!() - |> Jason.decode!() - - def center_rect({rect_width, rect_height}, {parent_width, parent_height}) do - { - div(parent_height - rect_height, 2), - div(parent_width - rect_width, 2) - } - end - end - end -end diff --git a/mix.exs b/mix.exs index fd5a4b8..e4b0631 100644 --- a/mix.exs +++ b/mix.exs @@ -27,7 +27,7 @@ defmodule Chessh.MixProject do # Run "mix help deps" to learn about dependencies. defp deps do [ - {:chess, "~> 0.4.1"}, + {:binbo, "~> 4.0.2"}, {:ecto, "~> 3.9"}, {:ecto_sql, "~> 3.9"}, {:postgrex, "~> 0.16.5"}, diff --git a/mix.lock b/mix.lock index 48fe5e1..cd09aef 100644 --- a/mix.lock +++ b/mix.lock @@ -1,5 +1,6 @@ %{ "bcrypt_elixir": {:hex, :bcrypt_elixir, "3.0.1", "9be815469e6bfefec40fa74658ecbbe6897acfb57614df1416eeccd4903f602c", [:make, :mix], [{:comeonin, "~> 5.3", [hex: :comeonin, repo: "hexpm", optional: false]}, {:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "486bb95efb645d1efc6794c1ddd776a186a9a713abf06f45708a6ce324fb96cf"}, + "binbo": {:hex, :binbo, "4.0.3", "f6d884e523504595f4445000c5520eb8532dafb94d34b7c572290795868a12e0", [:rebar3], [{:uef, "2.6.0", [hex: :uef, repo: "hexpm", optional: false]}], "hexpm", "3029775a3afaa3377a9ffac4973a3cfc7aa51c1f4b1ceebd2e546ad0161fe1bb"}, "chess": {:hex, :chess, "0.4.1", "34c04abed2db81e0c56476c8e74fd85ef4e1bae23a4cd528e0ce8a052ada976f", [:mix], [], "hexpm", "692e0def99dc25af4af2413839a4605a2a0a713c2646f9afcf3a47c76a6de43d"}, "comeonin": {:hex, :comeonin, "5.3.3", "2c564dac95a35650e9b6acfe6d2952083d8a08e4a89b93a481acb552b325892e", [:mix], [], "hexpm", "3e38c9c2cb080828116597ca8807bb482618a315bfafd98c90bc22a821cc84df"}, "connection": {:hex, :connection, "1.1.0", "ff2a49c4b75b6fb3e674bfc5536451607270aac754ffd1bdfe175abe4a6d7a68", [:mix], [], "hexpm", "722c1eb0a418fbe91ba7bd59a47e28008a189d47e37e0e7bb85585a016b2869c"}, @@ -16,4 +17,5 @@ "postgrex": {:hex, :postgrex, "0.16.5", "fcc4035cc90e23933c5d69a9cd686e329469446ef7abba2cf70f08e2c4b69810", [:mix], [{:connection, "~> 1.1", [hex: :connection, repo: "hexpm", optional: false]}, {:db_connection, "~> 2.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "edead639dc6e882618c01d8fc891214c481ab9a3788dfe38dd5e37fd1d5fb2e8"}, "syn": {:hex, :syn, "3.3.0", "4684a909efdfea35ce75a9662fc523e4a8a4e8169a3df275e4de4fa63f99c486", [:rebar3], [], "hexpm", "e58ee447bc1094bdd21bf0acc102b1fbf99541a508cd48060bf783c245eaf7d6"}, "telemetry": {:hex, :telemetry, "1.1.0", "a589817034a27eab11144ad24d5c0f9fab1f58173274b1e9bae7074af9cbee51", [:rebar3], [], "hexpm", "b727b2a1f75614774cff2d7565b64d0dfa5bd52ba517f16543e6fc7efcc0df48"}, + "uef": {:hex, :uef, "2.6.0", "0aa813d125c429e48c1d5abbab89837d8b7bd0499e6ee2f7dc9cc4287a475cfd", [:rebar3], [], "hexpm", "1585cba305dc7c0a3f75aeab15937b324184673d2922148b432edf9beba73d62"}, } From 628c6d95a32ba0dea67ab046a480ddfca7432c9b Mon Sep 17 00:00:00 2001 From: Simponic Date: Wed, 11 Jan 2023 14:21:48 -0700 Subject: [PATCH 06/12] Done moving menu to genserver architecture --- lib/chessh/ssh/client/client.ex | 79 +++++++++++++++++++++++---------- lib/chessh/ssh/client/menu.ex | 69 ++++++++++++++-------------- lib/chessh/ssh/client/screen.ex | 25 ++++++----- lib/chessh/ssh/tui.ex | 33 +++++++------- 4 files changed, 120 insertions(+), 86 deletions(-) diff --git a/lib/chessh/ssh/client/client.ex b/lib/chessh/ssh/client/client.ex index a5f7bec..216af71 100644 --- a/lib/chessh/ssh/client/client.ex +++ b/lib/chessh/ssh/client/client.ex @@ -1,22 +1,18 @@ defmodule Chessh.SSH.Client do alias IO.ANSI - alias Chessh.SSH.Client.Menu require Logger use GenServer @clear_codes [ ANSI.clear(), - ANSI.reset(), ANSI.home() ] - @max_terminal_width 255 - @max_terminal_height 127 - - @terminal_bad_dim_msg [ - @clear_codes | "The dimensions of your terminal are not within in the valid range" - ] + @min_terminal_width 64 + @min_terminal_height 31 + @max_terminal_width 200 + @max_terminal_height 100 defmodule State do defstruct tui_pid: nil, @@ -27,10 +23,10 @@ defmodule Chessh.SSH.Client do end @impl true - def init([%State{tui_pid: tui_pid} = state]) do + def init([%State{} = state]) do {:ok, screen_pid} = GenServer.start_link(Chessh.SSH.Client.Menu, [ - %Chessh.SSH.Client.Menu.State{tui_pid: tui_pid} + %Chessh.SSH.Client.Menu.State{client_pid: self()} ]) {:ok, %{state | screen_processes: [screen_pid]}} @@ -76,27 +72,36 @@ defmodule Chessh.SSH.Client do end end - # def handle( - # {:refresh, }, - # %State{screen_processes: [screen_pid | _] = screen_processes, width: width, height: height} = state - # ) do - # send(screen_pid, {:render, tui_pid, width, height}) - # {:noreply, state} - # end + def handle( + :refresh, + %State{} = state + ) do + render(state) + {:noreply, state} + end + + def handle( + {:send_to_ssh, data}, + %State{width: width, height: height, tui_pid: tui_pid} = state + ) do + case get_terminal_dim_msg(width, height) do + {true, msg} -> send(tui_pid, {:send_data, msg}) + {false, _} -> send(tui_pid, {:send_data, data}) + end + + {:noreply, state} + end def handle( {:resize, {width, height}}, %State{tui_pid: tui_pid, screen_processes: [screen_pid | _]} = state ) do - new_state = %State{state | width: width, height: height} - - if height <= @max_terminal_height && width <= @max_terminal_width do - send(screen_pid, {:render, width, height}) - else - send(tui_pid, {:send_data, @terminal_bad_dim_msg}) + case get_terminal_dim_msg(width, height) do + {true, msg} -> send(tui_pid, {:send_data, msg}) + {false, _} -> send(screen_pid, {:render, width, height}) end - {:noreply, new_state} + {:noreply, %State{state | width: width, height: height}} end def keymap(key) do @@ -113,4 +118,30 @@ defmodule Chessh.SSH.Client do x -> x end end + + defp get_terminal_dim_msg(width, height) do + case {height > @max_terminal_height, height < @min_terminal_height, + width > @max_terminal_width, width < @min_terminal_width} do + {true, _, _, _} -> {true, @clear_codes ++ ["The terminal height is too large."]} + {_, true, _, _} -> {true, @clear_codes ++ ["The terminal height is too small."]} + {_, _, true, _} -> {true, @clear_codes ++ ["The terminal width is too large"]} + {_, _, _, true} -> {true, @clear_codes ++ ["The terminal width is too small."]} + {false, false, false, false} -> {false, nil} + end + end + + defp render(%State{ + tui_pid: tui_pid, + width: width, + height: height, + screen_processes: [screen_pid | _] + }) do + {out_of_range, msg} = get_terminal_dim_msg(width, height) + + if out_of_range && msg do + send(tui_pid, {:send_data, msg}) + else + send(screen_pid, {:render, width, height}) + end + end end diff --git a/lib/chessh/ssh/client/menu.ex b/lib/chessh/ssh/client/menu.ex index a69ad88..7e2ffbc 100644 --- a/lib/chessh/ssh/client/menu.ex +++ b/lib/chessh/ssh/client/menu.ex @@ -5,18 +5,10 @@ defmodule Chessh.SSH.Client.Menu do require Logger defmodule State do - defstruct dy: 0, - dx: 0, - tui_pid: nil, + defstruct client_pid: nil, selected: 0 end - use Chessh.SSH.Client.Screen - - def init([%State{} = state | _]) do - {:ok, state} - end - @logo " Simponic's dP MP\"\"\"\"\"\"`MM MP\"\"\"\"\"\"`MM M\"\"MMMMM\"\"MM 88 M mmmmm..M M mmmmm..M M MMMMM MM @@ -25,6 +17,11 @@ defmodule Chessh.SSH.Client.Menu do 88. ... 88 88 88. ... M. .MMM' M M. .MMM' M M MMMMM MM `88888P' dP dP `88888P' Mb. .dM Mb. .dM M MMMMM MM MMMMMMMMMMM MMMMMMMMMMM MMMMMMMMMMMM" + use Chessh.SSH.Client.Screen + + def init([%State{} = state | _]) do + {:ok, state} + end # @options [ # {"Option 1", {Chessh.SSH.Client.Board, [%Chessh.SSH.Client.Board.State{}]}}, @@ -36,12 +33,7 @@ defmodule Chessh.SSH.Client.Menu do {"Option 3", {}} ] - def handle_info({:render, width, height}, %State{} = state) do - render(width, height, state) - {:noreply, state} - end - - def handle_info({:input, width, height, action}, %State{selected: selected} = state) do + def input(width, height, action, %State{client_pid: client_pid, selected: selected} = state) do new_state = case(action) do :up -> @@ -61,36 +53,43 @@ defmodule Chessh.SSH.Client.Menu do state end - render(width, height, new_state) - {:noreply, new_state} + send(client_pid, {:send_to_ssh, render_state(width, height, new_state)}) + new_state end - def render(width, height, %State{tui_pid: tui_pid, dy: dy, dx: dx, selected: selected}) do - text = String.split(@logo, "\n") - {logo_width, logo_height} = Utils.text_dim(@logo) - {y, x} = center_rect({logo_width, logo_height + length(text)}, {width, height}) + def render(width, height, %State{client_pid: client_pid} = state) do + send(client_pid, {:send_to_ssh, render_state(width, height, state)}) + state + end - rendered = + defp render_state( + width, + height, + %State{selected: selected} + ) do + logo_lines = String.split(@logo, "\n") + {logo_width, logo_height} = Utils.text_dim(@logo) + {y, x} = center_rect({logo_width, logo_height + length(logo_lines)}, {width, height}) + + [ANSI.clear()] ++ Enum.flat_map( - Enum.zip(1..length(text), text), + Enum.zip(1..length(logo_lines), logo_lines), fn {i, line} -> [ - ANSI.cursor(y + i + dy, x + dx), + ANSI.cursor(y + i, x), line ] end ) ++ - Enum.flat_map( - Enum.zip(0..(length(@options) - 1), @options), - fn {i, {option, _}} -> - [ - ANSI.cursor(y + length(text) + i + dy, x + dx), - if(i == selected, do: ANSI.format([:light_cyan, "* #{option}"]), else: option) - ] - end - ) ++ [ANSI.home()] - - send(tui_pid, {:send_data, rendered}) + Enum.flat_map( + Enum.zip(0..(length(@options) - 1), @options), + fn {i, {option, _}} -> + [ + ANSI.cursor(y + length(logo_lines) + i + 1, x), + if(i == selected, do: ANSI.format([:bright, :light_cyan, "+ #{option}"]), else: option) + ] + end + ) ++ [ANSI.home()] end defp wrap_around(index, delta, length) do diff --git a/lib/chessh/ssh/client/screen.ex b/lib/chessh/ssh/client/screen.ex index 2dd9f9c..8eb9f21 100644 --- a/lib/chessh/ssh/client/screen.ex +++ b/lib/chessh/ssh/client/screen.ex @@ -1,21 +1,18 @@ defmodule Chessh.SSH.Client.Screen do - @callback handle_info( - {:render, width :: integer(), height :: integer()}, - state :: any() - ) :: - {:noreply, any()} - @callback handle_info({:input, width :: integer(), height :: integer(), action :: any()}) :: - {:noreply, any()} - - # @callback render(state :: Chessh.SSH.Client.State.t() | any()) :: any() - # @callback handle_input(action :: any(), state :: Chessh.SSH.Client.State.t()) :: - # Chessh.SSH.Client.State.t() + @callback render(width :: integer(), height :: integer(), state :: any()) :: any() + @callback input(width :: integer(), height :: integer(), action :: any(), state :: any()) :: + any() defmacro __using__(_) do quote do @behaviour Chessh.SSH.Client.Screen use GenServer + @clear_codes [ + IO.ANSI.clear(), + IO.ANSI.home() + ] + @ascii_chars Application.compile_env!(:chessh, :ascii_chars_json_file) |> File.read!() |> Jason.decode!() @@ -26,6 +23,12 @@ defmodule Chessh.SSH.Client.Screen do div(parent_width - rect_width, 2) } end + + def handle_info({:render, width, height}, state), + do: {:noreply, render(width, height, state)} + + def handle_info({:input, width, height, action}, state), + do: {:noreply, input(width, height, action, state)} end end end diff --git a/lib/chessh/ssh/tui.ex b/lib/chessh/ssh/tui.ex index 5d43760..c1c763b 100644 --- a/lib/chessh/ssh/tui.ex +++ b/lib/chessh/ssh/tui.ex @@ -26,7 +26,7 @@ defmodule Chessh.SSH.Tui do {:ok, init_state} end - def handle_msg({:ssh_channel_up, channel_id, connection_ref}, state) do + def handle_msg({:ssh_channel_up, channel_id, connection_ref}, %State{} = state) do Logger.debug("SSH channel up #{inspect(:ssh.connection_info(connection_ref))}") connected_player = @@ -54,7 +54,7 @@ defmodule Chessh.SSH.Tui do :syn.join(:player_sessions, {:session, session.id}, self()) {:ok, - %{ + %State{ state | channel_id: channel_id, connection_ref: connection_ref, @@ -66,7 +66,7 @@ defmodule Chessh.SSH.Tui do def handle_msg( {:EXIT, client_pid, _reason}, - %{client_pid: client_pid, channel_id: channel_id} = state + %State{client_pid: client_pid, channel_id: channel_id} = state ) do send(client_pid, :quit) {:stop, channel_id, state} @@ -74,7 +74,7 @@ defmodule Chessh.SSH.Tui do def handle_msg( {:send_data, data}, - %{connection_ref: connection_ref, channel_id: channel_id} = state + %State{connection_ref: connection_ref, channel_id: channel_id} = state ) do :ssh_connection.send(connection_ref, channel_id, data) {:ok, state} @@ -82,7 +82,7 @@ defmodule Chessh.SSH.Tui do def handle_msg( :session_closed, - %{connection_ref: connection_ref, channel_id: channel_id} = state + %State{connection_ref: connection_ref, channel_id: channel_id} = state ) do :ssh_connection.send(connection_ref, channel_id, @session_closed_message) {:stop, channel_id, state} @@ -94,7 +94,7 @@ defmodule Chessh.SSH.Tui do def handle_ssh_msg( {:ssh_cm, _connection_handler, {:data, _channel_id, _type, data}}, - state + %State{} = state ) do send(state.client_pid, {:data, data}) {:ok, state} @@ -103,7 +103,7 @@ defmodule Chessh.SSH.Tui do def handle_ssh_msg( {:ssh_cm, connection_handler, {:pty, channel_id, want_reply?, {_term, width, height, _pixwidth, _pixheight, _opts}}}, - state + %State{client_pid: client_pid} = state ) do Logger.debug("#{inspect(state.player_session)} has requested a PTY") :ssh_connection.reply_request(connection_handler, want_reply?, :success, channel_id) @@ -128,12 +128,12 @@ defmodule Chessh.SSH.Tui do def handle_ssh_msg( {:ssh_cm, _connection_handler, {:window_change, _channel_id, width, height, _pixwidth, _pixheight}}, - %{client_pid: client_pid} = state + %State{client_pid: client_pid} = state ) do send(client_pid, {:resize, {width, height}}) {:ok, - %{ + %State{ state | width: width, height: height @@ -157,12 +157,13 @@ defmodule Chessh.SSH.Tui do } ]) - {:ok, %{state | client_pid: client_pid}} + send(client_pid, :refresh) + {:ok, %State{state | client_pid: client_pid}} end def handle_ssh_msg( {:ssh_cm, connection_handler, {:exec, channel_id, want_reply?, cmd}}, - state + %State{} = state ) do :ssh_connection.reply_request(connection_handler, want_reply?, :success, channel_id) Logger.debug("EXEC #{cmd}") @@ -171,7 +172,7 @@ defmodule Chessh.SSH.Tui do def handle_ssh_msg( {:ssh_cm, _connection_handler, {:eof, _channel_id}}, - state + %State{} = state ) do Logger.debug("EOF") {:ok, state} @@ -179,7 +180,7 @@ defmodule Chessh.SSH.Tui do def handle_ssh_msg( {:ssh_cm, _connection_handler, {:signal, _channel_id, signal}}, - state + %State{} = state ) do Logger.debug("SIGNAL #{signal}") {:ok, state} @@ -187,7 +188,7 @@ defmodule Chessh.SSH.Tui do def handle_ssh_msg( {:ssh_cm, _connection_handler, {:exit_signal, channel_id, signal, err, lang}}, - state + %State{} = state ) do Logger.debug("EXIT SIGNAL #{signal} #{err} #{lang}") {:stop, channel_id, state} @@ -195,7 +196,7 @@ defmodule Chessh.SSH.Tui do def handle_ssh_msg( {:ssh_cm, _connection_handler, {:exit_STATUS, channel_id, status}}, - state + %State{} = state ) do Logger.debug("EXIT STATUS #{status}") {:stop, channel_id, state} @@ -203,7 +204,7 @@ defmodule Chessh.SSH.Tui do def handle_ssh_msg( msg, - %{channel_id: channel_id} = state + %State{channel_id: channel_id} = state ) do Logger.debug("UNKOWN MESSAGE #{inspect(msg)}") {:stop, channel_id, state} From aa2ff6e1374e8a6a546aa04ee3430d1152c58553 Mon Sep 17 00:00:00 2001 From: Simponic Date: Wed, 11 Jan 2023 19:14:47 -0700 Subject: [PATCH 07/12] Checkpoint --- lib/chessh/ssh/client/board/board.ex | 113 +++++++++++++++++++++++++++ lib/chessh/ssh/client/client.ex | 4 +- lib/chessh/ssh/client/menu.ex | 4 - 3 files changed, 115 insertions(+), 6 deletions(-) create mode 100644 lib/chessh/ssh/client/board/board.ex diff --git a/lib/chessh/ssh/client/board/board.ex b/lib/chessh/ssh/client/board/board.ex new file mode 100644 index 0000000..600917f --- /dev/null +++ b/lib/chessh/ssh/client/board/board.ex @@ -0,0 +1,113 @@ +defmodule Chessh.SSH.Client.Board do + alias IO.ANSI + require Logger + + @chess_board_height 8 + @chess_board_width 8 + @tile_width 7 + @tile_height 4 + + @dark_piece_color ANSI.magenta() + @light_piece_color ANSI.red() + @from_select_background ANSI.green_background() + @to_select_background ANSI.blue_background() + + defmodule State do + defstruct cursor: %{x: 0, y: 0}, + highlighted: %{}, + move_from: nil, + game_id: nil, + client_pid: nil + end + + use Chessh.SSH.Client.Screen + + def init([%State{game_id: game_id} = state | _]) do + :syn.add_node_to_scopes([:games]) + :ok = :syn.join(:games, {:game, game_id}, self()) + + {:ok, state} + end + + def handle_info({:attempted_move, move}, %State{client_pid: client_pid} = state) do + send(client_pid, {:send_to_ssh, ["hello, world!"]}) + {:noreply, state} + end + + def input( + width, + height, + action, + %State{ + move_from: move_from, + game_id: game_id, + cursor: %{x: cursor_x, y: cursor_y} = cursor, + client_pid: client_pid + } = state + ) do + new_cursor = + case action do + :left -> %{y: cursor_y, x: cursor_x - 1} + :right -> %{y: cursor_y, x: cursor_x + 1} + :down -> %{y: cursor_y + 1, x: cursor_x} + :up -> %{y: cursor_y - 1, x: cursor_x} + _ -> cursor + end + + {new_move_from, move_to} = + if action == :return do + coords = {new_cursor.y, new_cursor.x} + + case move_from do + nil -> {coords, nil} + _ -> {nil, coords} + end + else + {move_from, nil} + end + + if move_from && move_to do + attempted_move = "#{to_chess_coord(move_from)}#{to_chess_coord(move_to)}" + :syn.publish(:games, {:game, game_id}, {:new_move, attempted_move}) + end + + new_state = %State{ + state + | cursor: new_cursor, + move_from: new_move_from, + highlighted: %{ + new_move_from => @from_select_background, + {new_cursor.y, new_cursor.x} => @to_select_background + } + } + + send(client_pid, {:send_to_ssh, render_state(width, height, new_state)}) + new_state + end + + def render(width, height, %State{client_pid: client_pid} = state) do + send(client_pid, {:send_to_ssh, render_state(width, height, state)}) + state + end + + defp render_state(width, height, %State{} = _state) do + [ANSI.clear(), "#{width}#{height}"] + end + + defp to_chess_coord({y, x}) + when x >= 0 and x < @chess_board_width and y >= 0 and y < @chess_board_height do + "#{List.to_string([?a + x])}#{y + 1}" + end + + defp piece_type(char) do + case String.capitalize(char) do + "P" -> "pawn" + "N" -> "knight" + "R" -> "rook" + "B" -> "bishop" + "K" -> "king" + "Q" -> "queen" + _ -> nil + end + end +end diff --git a/lib/chessh/ssh/client/client.ex b/lib/chessh/ssh/client/client.ex index 216af71..eff22b8 100644 --- a/lib/chessh/ssh/client/client.ex +++ b/lib/chessh/ssh/client/client.ex @@ -25,8 +25,8 @@ defmodule Chessh.SSH.Client do @impl true def init([%State{} = state]) do {:ok, screen_pid} = - GenServer.start_link(Chessh.SSH.Client.Menu, [ - %Chessh.SSH.Client.Menu.State{client_pid: self()} + GenServer.start_link(Chessh.SSH.Client.Board, [ + %Chessh.SSH.Client.Board.State{client_pid: self()} ]) {:ok, %{state | screen_processes: [screen_pid]}} diff --git a/lib/chessh/ssh/client/menu.ex b/lib/chessh/ssh/client/menu.ex index 7e2ffbc..70cbcce 100644 --- a/lib/chessh/ssh/client/menu.ex +++ b/lib/chessh/ssh/client/menu.ex @@ -23,10 +23,6 @@ defmodule Chessh.SSH.Client.Menu do {:ok, state} end - # @options [ - # {"Option 1", {Chessh.SSH.Client.Board, [%Chessh.SSH.Client.Board.State{}]}}, - # {"Option 2", {Chessh.SSH.Client.Board, [%Chessh.SSH.Client.Board.State{}]}} - # ] @options [ {"Option 1", {}}, {"Option 2", {}}, From a93119b25033248decda7477575e214a1b254fbd Mon Sep 17 00:00:00 2001 From: Simponic Date: Fri, 13 Jan 2023 10:00:58 -0700 Subject: [PATCH 08/12] Binbo start link --- lib/chessh/ssh/client/board.ex | 276 --------------------------- lib/chessh/ssh/client/board/board.ex | 219 +++++++++++++++++++-- lib/chessh/ssh/client/client.ex | 2 +- lib/chessh/ssh/client/menu.ex | 9 +- lib/chessh/utils.ex | 5 + 5 files changed, 211 insertions(+), 300 deletions(-) delete mode 100644 lib/chessh/ssh/client/board.ex diff --git a/lib/chessh/ssh/client/board.ex b/lib/chessh/ssh/client/board.ex deleted file mode 100644 index b192cfe..0000000 --- a/lib/chessh/ssh/client/board.ex +++ /dev/null @@ -1,276 +0,0 @@ -# defmodule Chessh.SSH.Client.Board do -# alias Chessh.SSH.Client -# alias IO.ANSI -# -# require Logger -# -# defmodule State do -# defstruct cursor: %{x: 0, y: 0}, -# highlighted: %{}, -# move_from: nil -# end -# -# use GenServer -# use Chessh.SSH.Client.Screen -# -# @chess_board_height 8 -# @chess_board_width 8 -# @tile_width 7 -# @tile_height 4 -# -# @dark_piece_color ANSI.magenta() -# @light_piece_color ANSI.red() -# -# def tileIsLight(row, col) do -# rem(row, 2) == rem(col, 2) -# end -# -# def piece_type(char) do -# case String.capitalize(char) do -# "P" -> "pawn" -# "N" -> "knight" -# "R" -> "rook" -# "B" -> "bishop" -# "K" -> "king" -# "Q" -> "queen" -# _ -> nil -# end -# end -# -# def make_board({tile_width, tile_height}) do -# rows = -# Enum.map(0..(@chess_board_height - 1), fn row -> -# Enum.map(0..(@chess_board_width - 1), fn col -> -# if(tileIsLight(row, col), do: ' ', else: '▊') -# |> List.duplicate(tile_width) -# end) -# |> Enum.join("") -# end) -# -# Enum.flat_map(rows, fn row -> Enum.map(1..tile_height, fn _ -> row end) end) -# end -# -# defp skip_cols_or_place_piece_reduce(char, {curr_column, data}, rowI) do -# case Integer.parse(char) do -# {skip, ""} -> -# {curr_column + skip, data} -# -# _ -> -# case piece_type(char) do -# nil -> -# {curr_column, data} -# -# type -> -# shade = if(char != String.capitalize(char), do: "light", else: "dark") -# -# {curr_column + 1, -# Map.put( -# data, -# "#{rowI}, #{curr_column}", -# {shade, type} -# )} -# end -# end -# end -# -# defp make_coordinate_to_piece_art_map(fen) do -# rows = -# String.split(fen, " ") -# |> List.first() -# |> String.split("/") -# -# Enum.zip(rows, 0..(length(rows) - 1)) -# |> Enum.map(fn {row, rowI} -> -# {@chess_board_height, pieces_per_row} = -# Enum.reduce( -# String.split(row, ""), -# {0, %{}}, -# &skip_cols_or_place_piece_reduce(&1, &2, rowI) -# ) -# -# pieces_per_row -# end) -# |> Enum.reduce(%{}, fn pieces_map_for_this_row, acc -> -# Map.merge(acc, pieces_map_for_this_row) -# end) -# end -# -# def draw_board( -# fen, -# {tile_width, tile_height} = tile_dims, -# highlights -# ) do -# coordinate_to_piece = make_coordinate_to_piece_art_map(fen) -# board = make_board(tile_dims) -# -# Enum.zip_with([board, 0..(length(board) - 1)], fn [rowStr, row] -> -# curr_y = div(row, tile_height) -# -# %{row_chars: row_chars} = -# Enum.reduce( -# Enum.zip(String.graphemes(rowStr), 0..(String.length(rowStr) - 1)), -# %{current_color: ANSI.black(), row_chars: []}, -# fn {char, col}, %{current_color: current_color, row_chars: row_chars} = row_state -> -# curr_x = div(col, tile_width) -# key = "#{curr_y}, #{curr_x}" -# relative_to_tile_col = col - curr_x * tile_width -# -# prefix = -# if relative_to_tile_col == 0 do -# case Map.fetch(highlights, {curr_y, curr_x}) do -# {:ok, color} -> -# color -# -# _ -> -# ANSI.default_background() -# end -# end -# -# case Map.fetch(coordinate_to_piece, key) do -# {:ok, {shade, type}} -> -# piece = @ascii_chars["pieces"][shade][type] -# piece_line = Enum.at(piece, row - curr_y * tile_height) -# -# piece_line_len = String.length(piece_line) -# pad_left_right = div(tile_width - piece_line_len, 2) -# -# if relative_to_tile_col >= pad_left_right && -# relative_to_tile_col < tile_width - pad_left_right do -# piece_char = String.at(piece_line, relative_to_tile_col - pad_left_right) -# new_char = if piece_char == " ", do: char, else: piece_char -# -# color = -# if piece_char == " ", -# do: ANSI.default_color(), -# else: if(shade == "dark", do: @dark_piece_color, else: @light_piece_color) -# -# if color != current_color do -# %{ -# row_state -# | current_color: color, -# row_chars: row_chars ++ [prefix, color, new_char] -# } -# else -# %{ -# row_state -# | current_color: current_color, -# row_chars: row_chars ++ [prefix, new_char] -# } -# end -# else -# %{ -# row_state -# | current_color: ANSI.default_color(), -# row_chars: row_chars ++ [prefix, ANSI.default_color(), char] -# } -# end -# -# _ -> -# if ANSI.white() != current_color do -# %{ -# row_state -# | current_color: ANSI.default_color(), -# row_chars: row_chars ++ [prefix, ANSI.default_color(), char] -# } -# else -# %{ -# row_state -# | row_chars: row_chars ++ [prefix, char] -# } -# end -# end -# end -# ) -# -# row_chars -# |> Enum.join("") -# end) -# end -# -# def render(%Client.State{ -# state_stack: [{_this_module, %State{highlighted: highlighted}} | _] -# }) do -# board = -# draw_board( -# "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", -# {@tile_width, @tile_height}, -# highlighted -# ) -# -# [ANSI.home()] ++ -# Enum.map( -# Enum.zip(1..length(board), board), -# fn {i, line} -> -# [ANSI.cursor(i, 0), line] -# end -# ) -# end -# -# def handle_input( -# action, -# %Client.State{ -# binbo_pid: binbo_pid, -# state_stack: [ -# {this_module, -# %State{ -# move_from: move_from, -# cursor: %{x: cursor_x, y: cursor_y} = cursor -# } = screen_state} -# | rest_stack -# ] -# } = state -# ) do -# new_cursor = -# case action do -# :left -> %{y: cursor_y, x: cursor_x - 1} -# :right -> %{y: cursor_y, x: cursor_x + 1} -# :down -> %{y: cursor_y + 1, x: cursor_x} -# :up -> %{y: cursor_y - 1, x: cursor_x} -# _ -> cursor -# end -# -# {new_move_from, move_to} = -# if action == :return do -# coords = {new_cursor.y, new_cursor.x} -# -# case move_from do -# nil -> {coords, nil} -# _ -> {nil, coords} -# end -# else -# {move_from, nil} -# end -# -# if move_from && move_to do -# # Logger.debug(inspect(attempt_move(%Chess.Game{}, move_from, move_to))) -# attempted_move = "#{to_chess_coord(move_from)}#{to_chess_coord(move_to)}" -# -# case :binbo.move(binbo_pid, attempted_move) do -# # state.game_id}, {:new_move, :attempted_move}) -# {:ok, _} -> :syn.publish(:games, {:game, "asdf"}, {:new_move, attempted_move}) -# end -# end -# -# %Client.State{ -# state -# | state_stack: [ -# {this_module, -# %State{ -# screen_state -# | cursor: new_cursor, -# move_from: new_move_from, -# highlighted: %{ -# new_move_from => ANSI.green_background(), -# {new_cursor.y, new_cursor.x} => ANSI.green_background() -# } -# }} -# | rest_stack -# ] -# } -# end -# -# defp to_chess_coord({y, x}) -# when x >= 0 and x < @chess_board_width and y >= 0 and y < @chess_board_height do -# "#{List.to_string([?a + x])}#{y + 1}" -# end -# end diff --git a/lib/chessh/ssh/client/board/board.ex b/lib/chessh/ssh/client/board/board.ex index 600917f..b7f6da6 100644 --- a/lib/chessh/ssh/client/board/board.ex +++ b/lib/chessh/ssh/client/board/board.ex @@ -1,6 +1,7 @@ defmodule Chessh.SSH.Client.Board do alias IO.ANSI require Logger + alias Chessh.Utils @chess_board_height 8 @chess_board_width 8 @@ -13,11 +14,14 @@ defmodule Chessh.SSH.Client.Board do @to_select_background ANSI.blue_background() defmodule State do - defstruct cursor: %{x: 0, y: 0}, + defstruct cursor: %{x: 7, y: 7}, highlighted: %{}, move_from: nil, game_id: nil, - client_pid: nil + client_pid: nil, + binbo_pid: nil, + width: 0, + height: 0 end use Chessh.SSH.Client.Screen @@ -26,11 +30,17 @@ defmodule Chessh.SSH.Client.Board do :syn.add_node_to_scopes([:games]) :ok = :syn.join(:games, {:game, game_id}, self()) - {:ok, state} + :binbo.start() + {:ok, binbo_pid} = :binbo.new_server() + :binbo.new_game(binbo_pid) + + {:ok, %State{state | binbo_pid: binbo_pid}} end - def handle_info({:attempted_move, move}, %State{client_pid: client_pid} = state) do - send(client_pid, {:send_to_ssh, ["hello, world!"]}) + def handle_info({:new_move, move}, %State{binbo_pid: binbo_pid, client_pid: client_pid} = state) do + :binbo.move(binbo_pid, move) + + send(client_pid, {:send_to_ssh, render_state(state)}) {:noreply, state} end @@ -47,10 +57,10 @@ defmodule Chessh.SSH.Client.Board do ) do new_cursor = case action do - :left -> %{y: cursor_y, x: cursor_x - 1} - :right -> %{y: cursor_y, x: cursor_x + 1} - :down -> %{y: cursor_y + 1, x: cursor_x} - :up -> %{y: cursor_y - 1, x: cursor_x} + :left -> %{y: cursor_y, x: Utils.wrap_around(cursor_x, -1, @chess_board_width)} + :right -> %{y: cursor_y, x: Utils.wrap_around(cursor_x, 1, @chess_board_width)} + :down -> %{y: Utils.wrap_around(cursor_y, 1, @chess_board_height), x: cursor_x} + :up -> %{y: Utils.wrap_around(cursor_y, -1, @chess_board_height), x: cursor_x} _ -> cursor end @@ -68,6 +78,7 @@ defmodule Chessh.SSH.Client.Board do if move_from && move_to do attempted_move = "#{to_chess_coord(move_from)}#{to_chess_coord(move_to)}" + Logger.debug("New move #{attempted_move}") :syn.publish(:games, {:game, game_id}, {:new_move, attempted_move}) end @@ -78,25 +89,201 @@ defmodule Chessh.SSH.Client.Board do highlighted: %{ new_move_from => @from_select_background, {new_cursor.y, new_cursor.x} => @to_select_background - } + }, + width: width, + height: height } - send(client_pid, {:send_to_ssh, render_state(width, height, new_state)}) + send(client_pid, {:send_to_ssh, render_state(new_state)}) new_state end def render(width, height, %State{client_pid: client_pid} = state) do - send(client_pid, {:send_to_ssh, render_state(width, height, state)}) - state + send(client_pid, {:send_to_ssh, render_state(state)}) + %State{state | width: width, height: height} end - defp render_state(width, height, %State{} = _state) do - [ANSI.clear(), "#{width}#{height}"] + defp render_state(%State{ + width: _width, + height: _height, + binbo_pid: binbo_pid, + highlighted: highlighted + }) do + {:ok, fen} = :binbo.get_fen(binbo_pid) + + board = + draw_board( + fen, + {@tile_width, @tile_height}, + highlighted + ) + + [ANSI.home()] ++ + Enum.map( + Enum.zip(1..length(board), board), + fn {i, line} -> + [ANSI.cursor(i, 0), line] + end + ) + end + + defp make_board({tile_width, tile_height}) do + rows = + Enum.map(0..(@chess_board_height - 1), fn row -> + Enum.map(0..(@chess_board_width - 1), fn col -> + if(tileIsLight(row, col), do: ' ', else: '▊') + |> List.duplicate(tile_width) + end) + |> Enum.join("") + end) + + Enum.flat_map(rows, fn row -> Enum.map(1..tile_height, fn _ -> row end) end) end defp to_chess_coord({y, x}) when x >= 0 and x < @chess_board_width and y >= 0 and y < @chess_board_height do - "#{List.to_string([?a + x])}#{y + 1}" + "#{List.to_string([?a + x])}#{@chess_board_height - y}" + end + + defp tileIsLight(row, col) do + rem(row, 2) == rem(col, 2) + end + + defp skip_cols_or_place_piece_reduce(char, {curr_column, data}, rowI) do + case Integer.parse(char) do + {skip, ""} -> + {curr_column + skip, data} + + _ -> + case piece_type(char) do + nil -> + {curr_column, data} + + type -> + shade = if(char != String.capitalize(char), do: "light", else: "dark") + + {curr_column + 1, + Map.put( + data, + "#{rowI}, #{curr_column}", + {shade, type} + )} + end + end + end + + defp make_coordinate_to_piece_art_map(fen) do + rows = + String.split(fen, " ") + |> List.first() + |> String.split("/") + + Enum.zip(rows, 0..(length(rows) - 1)) + |> Enum.map(fn {row, rowI} -> + {@chess_board_height, pieces_per_row} = + Enum.reduce( + String.split(row, ""), + {0, %{}}, + &skip_cols_or_place_piece_reduce(&1, &2, rowI) + ) + + pieces_per_row + end) + |> Enum.reduce(%{}, fn pieces_map_for_this_row, acc -> + Map.merge(acc, pieces_map_for_this_row) + end) + end + + defp draw_board( + fen, + {tile_width, tile_height} = tile_dims, + highlights + ) do + coordinate_to_piece = make_coordinate_to_piece_art_map(fen) + board = make_board(tile_dims) + + Enum.zip_with([board, 0..(length(board) - 1)], fn [rowStr, row] -> + curr_y = div(row, tile_height) + + %{row_chars: row_chars} = + Enum.reduce( + Enum.zip(String.graphemes(rowStr), 0..(String.length(rowStr) - 1)), + %{current_color: ANSI.black(), row_chars: []}, + fn {char, col}, %{current_color: current_color, row_chars: row_chars} = row_state -> + curr_x = div(col, tile_width) + key = "#{curr_y}, #{curr_x}" + relative_to_tile_col = col - curr_x * tile_width + + prefix = + if relative_to_tile_col == 0 do + case Map.fetch(highlights, {curr_y, curr_x}) do + {:ok, color} -> + color + + _ -> + ANSI.default_background() + end + end + + case Map.fetch(coordinate_to_piece, key) do + {:ok, {shade, type}} -> + piece = @ascii_chars["pieces"][shade][type] + piece_line = Enum.at(piece, row - curr_y * tile_height) + + piece_line_len = String.length(piece_line) + pad_left_right = div(tile_width - piece_line_len, 2) + + if relative_to_tile_col >= pad_left_right && + relative_to_tile_col < tile_width - pad_left_right do + piece_char = String.at(piece_line, relative_to_tile_col - pad_left_right) + new_char = if piece_char == " ", do: char, else: piece_char + + color = + if piece_char == " ", + do: ANSI.default_color(), + else: if(shade == "dark", do: @dark_piece_color, else: @light_piece_color) + + if color != current_color do + %{ + row_state + | current_color: color, + row_chars: row_chars ++ [prefix, color, new_char] + } + else + %{ + row_state + | current_color: current_color, + row_chars: row_chars ++ [prefix, new_char] + } + end + else + %{ + row_state + | current_color: ANSI.default_color(), + row_chars: row_chars ++ [prefix, ANSI.default_color(), char] + } + end + + _ -> + if ANSI.white() != current_color do + %{ + row_state + | current_color: ANSI.default_color(), + row_chars: row_chars ++ [prefix, ANSI.default_color(), char] + } + else + %{ + row_state + | row_chars: row_chars ++ [prefix, char] + } + end + end + end + ) + + row_chars + |> Enum.join("") + end) end defp piece_type(char) do diff --git a/lib/chessh/ssh/client/client.ex b/lib/chessh/ssh/client/client.ex index eff22b8..0560ce0 100644 --- a/lib/chessh/ssh/client/client.ex +++ b/lib/chessh/ssh/client/client.ex @@ -11,7 +11,7 @@ defmodule Chessh.SSH.Client do @min_terminal_width 64 @min_terminal_height 31 - @max_terminal_width 200 + @max_terminal_width 220 @max_terminal_height 100 defmodule State do diff --git a/lib/chessh/ssh/client/menu.ex b/lib/chessh/ssh/client/menu.ex index 70cbcce..6eb2bdd 100644 --- a/lib/chessh/ssh/client/menu.ex +++ b/lib/chessh/ssh/client/menu.ex @@ -35,11 +35,11 @@ defmodule Chessh.SSH.Client.Menu do :up -> %State{ state - | selected: wrap_around(selected, -1, length(@options)) + | selected: Utils.wrap_around(selected, -1, length(@options)) } :down -> - %State{state | selected: wrap_around(selected, 1, length(@options))} + %State{state | selected: Utils.wrap_around(selected, 1, length(@options))} # :return -> # {_, new_state} = Enum.at(@options, selected) @@ -87,9 +87,4 @@ defmodule Chessh.SSH.Client.Menu do end ) ++ [ANSI.home()] end - - defp wrap_around(index, delta, length) do - calc = index + delta - if(calc < 0, do: length, else: 0) + rem(calc, length) - end end diff --git a/lib/chessh/utils.ex b/lib/chessh/utils.ex index 3e83d5e..d1acf44 100644 --- a/lib/chessh/utils.ex +++ b/lib/chessh/utils.ex @@ -11,4 +11,9 @@ defmodule Chessh.Utils do split = String.split(text, "\n") {Enum.reduce(split, 0, fn x, acc -> max(acc, String.length(x)) end), length(split)} end + + def wrap_around(index, delta, length) do + calc = index + delta + if(calc < 0, do: length, else: 0) + rem(calc, length) + end end From 07eaad9b8ded7a719183eec84faaf5b168744f01 Mon Sep 17 00:00:00 2001 From: Logan Hunt Date: Fri, 13 Jan 2023 12:20:01 -0700 Subject: [PATCH 09/12] Move renderer to its own module --- lib/chessh/ssh/client/board/board.ex | 239 +++-------------------- lib/chessh/ssh/client/board/renderer.ex | 248 ++++++++++++++++++++++++ lib/chessh/ssh/client/client.ex | 2 +- lib/chessh/ssh/client/menu.ex | 2 +- lib/chessh/ssh/client/screen.ex | 16 -- lib/chessh/utils.ex | 19 ++ 6 files changed, 296 insertions(+), 230 deletions(-) create mode 100644 lib/chessh/ssh/client/board/renderer.ex diff --git a/lib/chessh/ssh/client/board/board.ex b/lib/chessh/ssh/client/board/board.ex index b7f6da6..4c57e07 100644 --- a/lib/chessh/ssh/client/board/board.ex +++ b/lib/chessh/ssh/client/board/board.ex @@ -1,17 +1,7 @@ defmodule Chessh.SSH.Client.Board do - alias IO.ANSI require Logger alias Chessh.Utils - - @chess_board_height 8 - @chess_board_width 8 - @tile_width 7 - @tile_height 4 - - @dark_piece_color ANSI.magenta() - @light_piece_color ANSI.red() - @from_select_background ANSI.green_background() - @to_select_background ANSI.blue_background() + alias Chessh.SSH.Client.Board.Renderer defmodule State do defstruct cursor: %{x: 7, y: 7}, @@ -22,6 +12,8 @@ defmodule Chessh.SSH.Client.Board do binbo_pid: nil, width: 0, height: 0 + + # flipped: false end use Chessh.SSH.Client.Screen @@ -38,9 +30,14 @@ defmodule Chessh.SSH.Client.Board do end def handle_info({:new_move, move}, %State{binbo_pid: binbo_pid, client_pid: client_pid} = state) do - :binbo.move(binbo_pid, move) + case :binbo.move(binbo_pid, move) do + {:ok, :continue} -> + send(client_pid, {:send_to_ssh, render_state(state)}) + + _ -> + nil + end - send(client_pid, {:send_to_ssh, render_state(state)}) {:noreply, state} end @@ -53,14 +50,15 @@ defmodule Chessh.SSH.Client.Board do game_id: game_id, cursor: %{x: cursor_x, y: cursor_y} = cursor, client_pid: client_pid + # flipped: flipped } = state ) do new_cursor = case action do - :left -> %{y: cursor_y, x: Utils.wrap_around(cursor_x, -1, @chess_board_width)} - :right -> %{y: cursor_y, x: Utils.wrap_around(cursor_x, 1, @chess_board_width)} - :down -> %{y: Utils.wrap_around(cursor_y, 1, @chess_board_height), x: cursor_x} - :up -> %{y: Utils.wrap_around(cursor_y, -1, @chess_board_height), x: cursor_x} + :left -> %{y: cursor_y, x: Utils.wrap_around(cursor_x, -1, Renderer.chess_board_width())} + :right -> %{y: cursor_y, x: Utils.wrap_around(cursor_x, 1, Renderer.chess_board_width())} + :down -> %{y: Utils.wrap_around(cursor_y, 1, Renderer.chess_board_height()), x: cursor_x} + :up -> %{y: Utils.wrap_around(cursor_y, -1, Renderer.chess_board_height()), x: cursor_x} _ -> cursor end @@ -76,9 +74,10 @@ defmodule Chessh.SSH.Client.Board do {move_from, nil} end + # TODO: Check move here, then publish new move, subscribers get from DB instead if move_from && move_to do - attempted_move = "#{to_chess_coord(move_from)}#{to_chess_coord(move_to)}" - Logger.debug("New move #{attempted_move}") + attempted_move = "#{Renderer.to_chess_coord(move_from)}#{Renderer.to_chess_coord(move_to)}" + :syn.publish(:games, {:game, game_id}, {:new_move, attempted_move}) end @@ -87,11 +86,12 @@ defmodule Chessh.SSH.Client.Board do | cursor: new_cursor, move_from: new_move_from, highlighted: %{ - new_move_from => @from_select_background, - {new_cursor.y, new_cursor.x} => @to_select_background + {new_cursor.y, new_cursor.x} => Renderer.to_select_background(), + new_move_from => Renderer.from_select_background() }, width: width, height: height + # flipped: if(action == "f", do: !flipped, else: flipped) } send(client_pid, {:send_to_ssh, render_state(new_state)}) @@ -103,198 +103,13 @@ defmodule Chessh.SSH.Client.Board do %State{state | width: width, height: height} end - defp render_state(%State{ - width: _width, - height: _height, - binbo_pid: binbo_pid, - highlighted: highlighted - }) do + defp render_state( + %State{ + binbo_pid: binbo_pid + } = state + ) do {:ok, fen} = :binbo.get_fen(binbo_pid) - board = - draw_board( - fen, - {@tile_width, @tile_height}, - highlighted - ) - - [ANSI.home()] ++ - Enum.map( - Enum.zip(1..length(board), board), - fn {i, line} -> - [ANSI.cursor(i, 0), line] - end - ) - end - - defp make_board({tile_width, tile_height}) do - rows = - Enum.map(0..(@chess_board_height - 1), fn row -> - Enum.map(0..(@chess_board_width - 1), fn col -> - if(tileIsLight(row, col), do: ' ', else: '▊') - |> List.duplicate(tile_width) - end) - |> Enum.join("") - end) - - Enum.flat_map(rows, fn row -> Enum.map(1..tile_height, fn _ -> row end) end) - end - - defp to_chess_coord({y, x}) - when x >= 0 and x < @chess_board_width and y >= 0 and y < @chess_board_height do - "#{List.to_string([?a + x])}#{@chess_board_height - y}" - end - - defp tileIsLight(row, col) do - rem(row, 2) == rem(col, 2) - end - - defp skip_cols_or_place_piece_reduce(char, {curr_column, data}, rowI) do - case Integer.parse(char) do - {skip, ""} -> - {curr_column + skip, data} - - _ -> - case piece_type(char) do - nil -> - {curr_column, data} - - type -> - shade = if(char != String.capitalize(char), do: "light", else: "dark") - - {curr_column + 1, - Map.put( - data, - "#{rowI}, #{curr_column}", - {shade, type} - )} - end - end - end - - defp make_coordinate_to_piece_art_map(fen) do - rows = - String.split(fen, " ") - |> List.first() - |> String.split("/") - - Enum.zip(rows, 0..(length(rows) - 1)) - |> Enum.map(fn {row, rowI} -> - {@chess_board_height, pieces_per_row} = - Enum.reduce( - String.split(row, ""), - {0, %{}}, - &skip_cols_or_place_piece_reduce(&1, &2, rowI) - ) - - pieces_per_row - end) - |> Enum.reduce(%{}, fn pieces_map_for_this_row, acc -> - Map.merge(acc, pieces_map_for_this_row) - end) - end - - defp draw_board( - fen, - {tile_width, tile_height} = tile_dims, - highlights - ) do - coordinate_to_piece = make_coordinate_to_piece_art_map(fen) - board = make_board(tile_dims) - - Enum.zip_with([board, 0..(length(board) - 1)], fn [rowStr, row] -> - curr_y = div(row, tile_height) - - %{row_chars: row_chars} = - Enum.reduce( - Enum.zip(String.graphemes(rowStr), 0..(String.length(rowStr) - 1)), - %{current_color: ANSI.black(), row_chars: []}, - fn {char, col}, %{current_color: current_color, row_chars: row_chars} = row_state -> - curr_x = div(col, tile_width) - key = "#{curr_y}, #{curr_x}" - relative_to_tile_col = col - curr_x * tile_width - - prefix = - if relative_to_tile_col == 0 do - case Map.fetch(highlights, {curr_y, curr_x}) do - {:ok, color} -> - color - - _ -> - ANSI.default_background() - end - end - - case Map.fetch(coordinate_to_piece, key) do - {:ok, {shade, type}} -> - piece = @ascii_chars["pieces"][shade][type] - piece_line = Enum.at(piece, row - curr_y * tile_height) - - piece_line_len = String.length(piece_line) - pad_left_right = div(tile_width - piece_line_len, 2) - - if relative_to_tile_col >= pad_left_right && - relative_to_tile_col < tile_width - pad_left_right do - piece_char = String.at(piece_line, relative_to_tile_col - pad_left_right) - new_char = if piece_char == " ", do: char, else: piece_char - - color = - if piece_char == " ", - do: ANSI.default_color(), - else: if(shade == "dark", do: @dark_piece_color, else: @light_piece_color) - - if color != current_color do - %{ - row_state - | current_color: color, - row_chars: row_chars ++ [prefix, color, new_char] - } - else - %{ - row_state - | current_color: current_color, - row_chars: row_chars ++ [prefix, new_char] - } - end - else - %{ - row_state - | current_color: ANSI.default_color(), - row_chars: row_chars ++ [prefix, ANSI.default_color(), char] - } - end - - _ -> - if ANSI.white() != current_color do - %{ - row_state - | current_color: ANSI.default_color(), - row_chars: row_chars ++ [prefix, ANSI.default_color(), char] - } - else - %{ - row_state - | row_chars: row_chars ++ [prefix, char] - } - end - end - end - ) - - row_chars - |> Enum.join("") - end) - end - - defp piece_type(char) do - case String.capitalize(char) do - "P" -> "pawn" - "N" -> "knight" - "R" -> "rook" - "B" -> "bishop" - "K" -> "king" - "Q" -> "queen" - _ -> nil - end + Renderer.render_board_state(fen, state) end end diff --git a/lib/chessh/ssh/client/board/renderer.ex b/lib/chessh/ssh/client/board/renderer.ex new file mode 100644 index 0000000..16987c7 --- /dev/null +++ b/lib/chessh/ssh/client/board/renderer.ex @@ -0,0 +1,248 @@ +defmodule Chessh.SSH.Client.Board.Renderer do + alias IO.ANSI + alias Chessh.Utils + alias Chessh.SSH.Client.Board + + @chess_board_height 8 + @chess_board_width 8 + + @tile_width 7 + @tile_height 4 + + @from_select_background ANSI.green_background() + @to_select_background ANSI.blue_background() + @dark_piece_color ANSI.red() + @light_piece_color ANSI.magenta() + + def chess_board_height(), do: @chess_board_height + def chess_board_width(), do: @chess_board_width + def to_select_background(), do: @to_select_background + def from_select_background(), do: @from_select_background + + def to_chess_coord({y, x}) + when x >= 0 and x < @chess_board_width and y >= 0 and y < @chess_board_height do + "#{List.to_string([?a + x])}#{@chess_board_height - y}" + end + + def render_board_state(fen, %Board.State{ + width: _width, + height: _height, + highlighted: highlighted + }) do + board = + draw_board( + fen, + {@tile_width, @tile_height}, + highlighted + ) + + [ANSI.home()] ++ + Enum.map( + Enum.zip(1..length(board), board), + fn {i, line} -> + [ANSI.cursor(i, 0), line] + end + ) + end + + defp tileIsLight(row, col) do + rem(row, 2) == rem(col, 2) + end + + defp piece_type(char) do + case String.capitalize(char) do + "P" -> "pawn" + "N" -> "knight" + "R" -> "rook" + "B" -> "bishop" + "K" -> "king" + "Q" -> "queen" + _ -> nil + end + end + + defp skip_cols_or_place_piece_reduce(char, {curr_column, data}, rowI) do + case Integer.parse(char) do + {skip, ""} -> + {curr_column + skip, data} + + _ -> + case piece_type(char) do + nil -> + {curr_column, data} + + type -> + shade = if(char == String.capitalize(char), do: "light", else: "dark") + + {curr_column + 1, + Map.put( + data, + "#{rowI}, #{curr_column}", + {shade, type} + )} + end + end + end + + defp make_coordinate_to_piece_art_map(fen) do + rows = + String.split(fen, " ") + |> List.first() + |> String.split("/") + + Enum.zip(rows, 0..(length(rows) - 1)) + |> Enum.map(fn {row, rowI} -> + {@chess_board_height, pieces_per_row} = + Enum.reduce( + String.split(row, ""), + {0, %{}}, + &skip_cols_or_place_piece_reduce(&1, &2, rowI) + ) + + pieces_per_row + end) + |> Enum.reduce(%{}, fn pieces_map_for_this_row, acc -> + Map.merge(acc, pieces_map_for_this_row) + end) + end + + defp draw_board( + fen, + {tile_width, tile_height} = tile_dims, + highlights + ) do + coordinate_to_piece = make_coordinate_to_piece_art_map(fen) + board = make_board(tile_dims) + + (Enum.zip_with([board, 0..(length(board) - 1)], fn [row_str, row] -> + curr_y = div(row, tile_height) + + %{row_chars: row_chars} = + Enum.reduce( + Enum.zip(String.graphemes(row_str), 0..(String.length(row_str) - 1)), + %{current_color: ANSI.black(), row_chars: []}, + fn {char, col}, %{current_color: current_color, row_chars: row_chars} = row_state -> + curr_x = div(col, tile_width) + key = "#{curr_y}, #{curr_x}" + relative_to_tile_col = col - curr_x * tile_width + + prefix = + if relative_to_tile_col == 0 do + case Map.fetch(highlights, {curr_y, curr_x}) do + {:ok, color} -> + color + + _ -> + ANSI.default_background() + end + end + + case Map.fetch(coordinate_to_piece, key) do + {:ok, {shade, type}} -> + piece = Utils.ascii_chars()["pieces"][shade][type] + piece_line = Enum.at(piece, row - curr_y * tile_height) + + piece_line_len = String.length(piece_line) + pad_left_right = div(tile_width - piece_line_len, 2) + + if relative_to_tile_col >= pad_left_right && + relative_to_tile_col < tile_width - pad_left_right do + piece_char = String.at(piece_line, relative_to_tile_col - pad_left_right) + new_char = if piece_char == " ", do: char, else: piece_char + + color = + if piece_char == " ", + do: ANSI.default_color(), + else: if(shade == "dark", do: @dark_piece_color, else: @light_piece_color) + + if color != current_color do + %{ + row_state + | current_color: color, + row_chars: row_chars ++ [prefix, color, new_char] + } + else + %{ + row_state + | current_color: current_color, + row_chars: row_chars ++ [prefix, new_char] + } + end + else + %{ + row_state + | current_color: ANSI.default_color(), + row_chars: row_chars ++ [prefix, ANSI.default_color(), char] + } + end + + _ -> + if ANSI.white() != current_color do + %{ + row_state + | current_color: ANSI.default_color(), + row_chars: row_chars ++ [prefix, ANSI.default_color(), char] + } + else + %{ + row_state + | row_chars: row_chars ++ [prefix, char] + } + end + end + end + ) + + curr_num = Utils.ascii_chars()["numbers"][Integer.to_string(curr_y)] + curr_num_line_no = rem(row, @tile_height) + + Enum.join( + [ + String.pad_trailing( + if(curr_num_line_no < length(curr_num), + do: Enum.at(curr_num, curr_num_line_no), + else: "" + ), + @tile_width + ) + ] ++ row_chars, + "" + ) + end) ++ + Enum.map(0..(@tile_height - 1), fn row -> + String.duplicate(" ", @tile_width) <> + (Enum.map(0..(@chess_board_width - 1), fn col -> + curr_letter = Utils.ascii_chars()["letters"][List.to_string([?a + col])] + curr_letter_line_no = rem(row, @tile_height) + + curr_line = + if(curr_letter_line_no < length(curr_letter), + do: Enum.at(curr_letter, curr_letter_line_no), + else: "" + ) + + center_prefix_len = div(@tile_width - String.length(curr_line), 2) + + String.pad_trailing( + String.duplicate(" ", center_prefix_len) <> curr_line, + @tile_width + ) + end) + |> Enum.join("")) + end)) + |> Enum.map(fn row_line -> "#{ANSI.default_background()}#{row_line}" end) + end + + defp make_board({tile_width, tile_height}) do + rows = + Enum.map(0..(@chess_board_height - 1), fn row -> + Enum.map(0..(@chess_board_width - 1), fn col -> + if(tileIsLight(row, col), do: '▊', else: ' ') + |> List.duplicate(tile_width) + end) + |> Enum.join("") + end) + + Enum.flat_map(rows, fn row -> Enum.map(1..tile_height, fn _ -> row end) end) + end +end diff --git a/lib/chessh/ssh/client/client.ex b/lib/chessh/ssh/client/client.ex index 0560ce0..10dd3b2 100644 --- a/lib/chessh/ssh/client/client.ex +++ b/lib/chessh/ssh/client/client.ex @@ -10,7 +10,7 @@ defmodule Chessh.SSH.Client do ] @min_terminal_width 64 - @min_terminal_height 31 + @min_terminal_height 38 @max_terminal_width 220 @max_terminal_height 100 diff --git a/lib/chessh/ssh/client/menu.ex b/lib/chessh/ssh/client/menu.ex index 6eb2bdd..c207872 100644 --- a/lib/chessh/ssh/client/menu.ex +++ b/lib/chessh/ssh/client/menu.ex @@ -65,7 +65,7 @@ defmodule Chessh.SSH.Client.Menu do ) do logo_lines = String.split(@logo, "\n") {logo_width, logo_height} = Utils.text_dim(@logo) - {y, x} = center_rect({logo_width, logo_height + length(logo_lines)}, {width, height}) + {y, x} = Utils.center_rect({logo_width, logo_height + length(logo_lines)}, {width, height}) [ANSI.clear()] ++ Enum.flat_map( diff --git a/lib/chessh/ssh/client/screen.ex b/lib/chessh/ssh/client/screen.ex index 8eb9f21..0437b23 100644 --- a/lib/chessh/ssh/client/screen.ex +++ b/lib/chessh/ssh/client/screen.ex @@ -8,22 +8,6 @@ defmodule Chessh.SSH.Client.Screen do @behaviour Chessh.SSH.Client.Screen use GenServer - @clear_codes [ - IO.ANSI.clear(), - IO.ANSI.home() - ] - - @ascii_chars Application.compile_env!(:chessh, :ascii_chars_json_file) - |> File.read!() - |> Jason.decode!() - - def center_rect({rect_width, rect_height}, {parent_width, parent_height}) do - { - div(parent_height - rect_height, 2), - div(parent_width - rect_width, 2) - } - end - def handle_info({:render, width, height}, state), do: {:noreply, render(width, height, state)} diff --git a/lib/chessh/utils.ex b/lib/chessh/utils.ex index d1acf44..20a8b96 100644 --- a/lib/chessh/utils.ex +++ b/lib/chessh/utils.ex @@ -1,4 +1,23 @@ defmodule Chessh.Utils do + @ascii_chars Application.compile_env!(:chessh, :ascii_chars_json_file) + |> File.read!() + |> Jason.decode!() + + @clear_codes [ + IO.ANSI.clear(), + IO.ANSI.home() + ] + + def ascii_chars(), do: @ascii_chars + def clear_codes(), do: @clear_codes + + def center_rect({rect_width, rect_height}, {parent_width, parent_height}) do + { + div(parent_height - rect_height, 2), + div(parent_width - rect_width, 2) + } + end + def pid_to_str(pid) do pid |> :erlang.pid_to_list() From b072f8421ce3caf4e00b3d6881259f595f57c045 Mon Sep 17 00:00:00 2001 From: Simponic Date: Fri, 13 Jan 2023 13:49:24 -0700 Subject: [PATCH 10/12] Add flipped --- lib/chessh/ssh/client/board/board.ex | 26 ++-- lib/chessh/ssh/client/board/renderer.ex | 160 +++++++++++++----------- 2 files changed, 103 insertions(+), 83 deletions(-) diff --git a/lib/chessh/ssh/client/board/board.ex b/lib/chessh/ssh/client/board/board.ex index 4c57e07..cbbade5 100644 --- a/lib/chessh/ssh/client/board/board.ex +++ b/lib/chessh/ssh/client/board/board.ex @@ -11,14 +11,13 @@ defmodule Chessh.SSH.Client.Board do client_pid: nil, binbo_pid: nil, width: 0, - height: 0 - - # flipped: false + height: 0, + flipped: false end use Chessh.SSH.Client.Screen - def init([%State{game_id: game_id} = state | _]) do + def init([%State{client_pid: client_pid, game_id: game_id} = state | _]) do :syn.add_node_to_scopes([:games]) :ok = :syn.join(:games, {:game, game_id}, self()) @@ -26,6 +25,8 @@ defmodule Chessh.SSH.Client.Board do {:ok, binbo_pid} = :binbo.new_server() :binbo.new_game(binbo_pid) + send(client_pid, {:send_to_ssh, Utils.clear_codes()}) + {:ok, %State{state | binbo_pid: binbo_pid}} end @@ -49,8 +50,8 @@ defmodule Chessh.SSH.Client.Board do move_from: move_from, game_id: game_id, cursor: %{x: cursor_x, y: cursor_y} = cursor, - client_pid: client_pid - # flipped: flipped + client_pid: client_pid, + flipped: flipped } = state ) do new_cursor = @@ -76,7 +77,11 @@ defmodule Chessh.SSH.Client.Board do # TODO: Check move here, then publish new move, subscribers get from DB instead if move_from && move_to do - attempted_move = "#{Renderer.to_chess_coord(move_from)}#{Renderer.to_chess_coord(move_to)}" + attempted_move = + if flipped, + do: + "#{Renderer.to_chess_coord(flip(move_from))}#{Renderer.to_chess_coord(flip(move_to))}", + else: "#{Renderer.to_chess_coord(move_from)}#{Renderer.to_chess_coord(move_to)}" :syn.publish(:games, {:game, game_id}, {:new_move, attempted_move}) end @@ -90,8 +95,8 @@ defmodule Chessh.SSH.Client.Board do new_move_from => Renderer.from_select_background() }, width: width, - height: height - # flipped: if(action == "f", do: !flipped, else: flipped) + height: height, + flipped: if(action == "f", do: !flipped, else: flipped) } send(client_pid, {:send_to_ssh, render_state(new_state)}) @@ -103,6 +108,9 @@ defmodule Chessh.SSH.Client.Board do %State{state | width: width, height: height} end + def flip({y, x}), + do: {Renderer.chess_board_height() - 1 - y, Renderer.chess_board_width() - 1 - x} + defp render_state( %State{ binbo_pid: binbo_pid diff --git a/lib/chessh/ssh/client/board/renderer.ex b/lib/chessh/ssh/client/board/renderer.ex index 16987c7..8c0267c 100644 --- a/lib/chessh/ssh/client/board/renderer.ex +++ b/lib/chessh/ssh/client/board/renderer.ex @@ -2,6 +2,7 @@ defmodule Chessh.SSH.Client.Board.Renderer do alias IO.ANSI alias Chessh.Utils alias Chessh.SSH.Client.Board + require Logger @chess_board_height 8 @chess_board_width 8 @@ -27,13 +28,15 @@ defmodule Chessh.SSH.Client.Board.Renderer do def render_board_state(fen, %Board.State{ width: _width, height: _height, - highlighted: highlighted + highlighted: highlighted, + flipped: flipped }) do board = draw_board( fen, {@tile_width, @tile_height}, - highlighted + highlighted, + flipped ) [ANSI.home()] ++ @@ -109,7 +112,8 @@ defmodule Chessh.SSH.Client.Board.Renderer do defp draw_board( fen, {tile_width, tile_height} = tile_dims, - highlights + highlights, + flipped ) do coordinate_to_piece = make_coordinate_to_piece_art_map(fen) board = make_board(tile_dims) @@ -123,7 +127,10 @@ defmodule Chessh.SSH.Client.Board.Renderer do %{current_color: ANSI.black(), row_chars: []}, fn {char, col}, %{current_color: current_color, row_chars: row_chars} = row_state -> curr_x = div(col, tile_width) - key = "#{curr_y}, #{curr_x}" + + key = + "#{if !flipped, do: curr_y, else: @chess_board_height - curr_y - 1}, #{if !flipped, do: curr_x, else: @chess_board_width - curr_x - 1}" + relative_to_tile_col = col - curr_x * tile_width prefix = @@ -137,63 +144,54 @@ defmodule Chessh.SSH.Client.Board.Renderer do end end - case Map.fetch(coordinate_to_piece, key) do - {:ok, {shade, type}} -> - piece = Utils.ascii_chars()["pieces"][shade][type] - piece_line = Enum.at(piece, row - curr_y * tile_height) + {color, row_chars} = + case Map.fetch(coordinate_to_piece, key) do + {:ok, {shade, type}} -> + piece = Utils.ascii_chars()["pieces"][shade][type] + piece_line = Enum.at(piece, row - curr_y * tile_height) + pad_left_right = div(tile_width - String.length(piece_line), 2) - piece_line_len = String.length(piece_line) - pad_left_right = div(tile_width - piece_line_len, 2) + if relative_to_tile_col >= pad_left_right && + relative_to_tile_col < tile_width - pad_left_right do + piece_char = String.at(piece_line, relative_to_tile_col - pad_left_right) + new_char = if piece_char == " ", do: char, else: piece_char - if relative_to_tile_col >= pad_left_right && - relative_to_tile_col < tile_width - pad_left_right do - piece_char = String.at(piece_line, relative_to_tile_col - pad_left_right) - new_char = if piece_char == " ", do: char, else: piece_char + color = + if piece_char == " ", + do: ANSI.default_color(), + else: + if(shade == "dark", do: @dark_piece_color, else: @light_piece_color) - color = - if piece_char == " ", - do: ANSI.default_color(), - else: if(shade == "dark", do: @dark_piece_color, else: @light_piece_color) - - if color != current_color do - %{ - row_state - | current_color: color, - row_chars: row_chars ++ [prefix, color, new_char] - } + if color != current_color do + {color, row_chars ++ [prefix, color, new_char]} + else + {current_color, row_chars ++ [prefix, new_char]} + end else - %{ - row_state - | current_color: current_color, - row_chars: row_chars ++ [prefix, new_char] - } + {ANSI.default_color(), row_chars ++ [prefix, ANSI.default_color(), char]} end - else - %{ - row_state - | current_color: ANSI.default_color(), - row_chars: row_chars ++ [prefix, ANSI.default_color(), char] - } - end - _ -> - if ANSI.white() != current_color do - %{ - row_state - | current_color: ANSI.default_color(), - row_chars: row_chars ++ [prefix, ANSI.default_color(), char] - } - else - %{ - row_state - | row_chars: row_chars ++ [prefix, char] - } - end - end + _ -> + if ANSI.default_color() != current_color do + {ANSI.default_color(), row_chars ++ [prefix, ANSI.default_color(), char]} + else + {current_color, row_chars ++ [prefix, char]} + end + end + + %{ + row_state + | current_color: color, + row_chars: row_chars + } end ) - curr_num = Utils.ascii_chars()["numbers"][Integer.to_string(curr_y)] + curr_num = + Utils.ascii_chars()["numbers"][ + Integer.to_string(if flipped, do: curr_y + 1, else: @chess_board_height - curr_y) + ] + curr_num_line_no = rem(row, @tile_height) Enum.join( @@ -208,31 +206,45 @@ defmodule Chessh.SSH.Client.Board.Renderer do ] ++ row_chars, "" ) - end) ++ - Enum.map(0..(@tile_height - 1), fn row -> - String.duplicate(" ", @tile_width) <> - (Enum.map(0..(@chess_board_width - 1), fn col -> - curr_letter = Utils.ascii_chars()["letters"][List.to_string([?a + col])] - curr_letter_line_no = rem(row, @tile_height) - - curr_line = - if(curr_letter_line_no < length(curr_letter), - do: Enum.at(curr_letter, curr_letter_line_no), - else: "" - ) - - center_prefix_len = div(@tile_width - String.length(curr_line), 2) - - String.pad_trailing( - String.duplicate(" ", center_prefix_len) <> curr_line, - @tile_width - ) - end) - |> Enum.join("")) - end)) + end) ++ column_coords(flipped)) |> Enum.map(fn row_line -> "#{ANSI.default_background()}#{row_line}" end) end + defp column_coords(flipped) do + Enum.map(0..(@tile_height - 1), fn row -> + String.duplicate(" ", @tile_width) <> + (Enum.map( + if(!flipped, do: 0..(@chess_board_width - 1), else: (@chess_board_width - 1)..0), + fn col -> + curr_letter = Utils.ascii_chars()["letters"][List.to_string([?a + col])] + curr_letter_line_no = rem(row, @tile_height) + + curr_line = + if(curr_letter_line_no < length(curr_letter), + do: Enum.at(curr_letter, curr_letter_line_no), + else: "" + ) + + center_prefix_len = div(@tile_width - String.length(curr_line), 2) + + String.pad_trailing( + String.duplicate(" ", center_prefix_len) <> curr_line, + @tile_width + ) + end + ) + |> Enum.join("")) + end) + end + + defp render_flipped(rows, flipped) do + if !flipped do + rows + else + rows + end + end + defp make_board({tile_width, tile_height}) do rows = Enum.map(0..(@chess_board_height - 1), fn row -> From 80843947e05cc464f54df7ad6838f5a16d9e7133 Mon Sep 17 00:00:00 2001 From: Logan Hunt Date: Fri, 13 Jan 2023 16:44:45 -0700 Subject: [PATCH 11/12] Remove warnings --- lib/chessh/ssh/client/board/renderer.ex | 8 -------- lib/chessh/ssh/tui.ex | 2 +- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/lib/chessh/ssh/client/board/renderer.ex b/lib/chessh/ssh/client/board/renderer.ex index 8c0267c..845e538 100644 --- a/lib/chessh/ssh/client/board/renderer.ex +++ b/lib/chessh/ssh/client/board/renderer.ex @@ -237,14 +237,6 @@ defmodule Chessh.SSH.Client.Board.Renderer do end) end - defp render_flipped(rows, flipped) do - if !flipped do - rows - else - rows - end - end - defp make_board({tile_width, tile_height}) do rows = Enum.map(0..(@chess_board_height - 1), fn row -> diff --git a/lib/chessh/ssh/tui.ex b/lib/chessh/ssh/tui.ex index c1c763b..1838fb8 100644 --- a/lib/chessh/ssh/tui.ex +++ b/lib/chessh/ssh/tui.ex @@ -103,7 +103,7 @@ defmodule Chessh.SSH.Tui do def handle_ssh_msg( {:ssh_cm, connection_handler, {:pty, channel_id, want_reply?, {_term, width, height, _pixwidth, _pixheight, _opts}}}, - %State{client_pid: client_pid} = state + %State{} = state ) do Logger.debug("#{inspect(state.player_session)} has requested a PTY") :ssh_connection.reply_request(connection_handler, want_reply?, :success, channel_id) From 3a6c603b0b12964d8a04ae4f78fb61bc094adf12 Mon Sep 17 00:00:00 2001 From: Logan Hunt Date: Fri, 13 Jan 2023 17:02:11 -0700 Subject: [PATCH 12/12] Change some colors around --- lib/chessh/ssh/client/board/renderer.ex | 6 +++--- priv/ascii_chars.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/chessh/ssh/client/board/renderer.ex b/lib/chessh/ssh/client/board/renderer.ex index 845e538..fa8648f 100644 --- a/lib/chessh/ssh/client/board/renderer.ex +++ b/lib/chessh/ssh/client/board/renderer.ex @@ -10,10 +10,10 @@ defmodule Chessh.SSH.Client.Board.Renderer do @tile_width 7 @tile_height 4 - @from_select_background ANSI.green_background() + @from_select_background ANSI.light_blue_background() @to_select_background ANSI.blue_background() - @dark_piece_color ANSI.red() - @light_piece_color ANSI.magenta() + @dark_piece_color ANSI.light_red() + @light_piece_color ANSI.light_magenta() def chess_board_height(), do: @chess_board_height def chess_board_width(), do: @chess_board_width diff --git a/priv/ascii_chars.json b/priv/ascii_chars.json index 1be31f8..fe7d12e 100644 --- a/priv/ascii_chars.json +++ b/priv/ascii_chars.json @@ -7,7 +7,7 @@ "e": [" __ ", "|_ ", "|__ "], "f": [" __ ", "|_ ", "| "], "g": [" __ ", "/ _ ", "\\__\\"], - "h": ["| |", "|__|", "| |"] + "h": [". .", "|__|", "| |"] }, "numbers": { "0": [" _ ", "| |", "|_|"],