fours 0.1.0

Four in a row in your terminal, with three levels of opponent.
Documentation
//! Where everything goes on the screen.
//!
//! The geometry is separate from the drawing so that both the front end and its tests agree on
//! what "centred" means without inspecting pixels.

use crate::bot::Difficulty;
use crate::game::BoardDimensions;
use crate::game::Cell;
use ratatui::layout::Rect;

/// How big the board is drawn.
///
/// The board takes the largest scale the terminal has room for, so a roomy window gets a board
/// with some weight to it without a small one losing anything.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Scale {
    /// A slot five columns wide and two rows tall.
    #[default]
    Normal,
    /// A slot seven columns wide and three rows tall.
    Large,
}

impl Scale {
    /// Every scale, from the smallest up.
    pub const ALL: [Self; 2] = [Self::Normal, Self::Large];

    /// The width of one slot of the board, in terminal columns.
    pub const fn cell_width(self) -> u16 {
        match self {
            Self::Normal => 5,
            Self::Large => 7,
        }
    }

    /// The height of one slot of the board, in terminal rows.
    pub const fn cell_height(self) -> u16 {
        match self {
            Self::Normal => 2,
            Self::Large => 3,
        }
    }
}

/// The title above the board.
pub const TITLE: &str = "F O U R S";

/// The key bindings below the board.
pub const HELP: &str = "←/→ move    ⏎ place    (d)ifficulty    (r)estart    (q)uit";

/// The rows above the board: the title, the opponent and the row that marks the selected column.
const ROWS_ABOVE_BOARD: u16 = 3;

/// The rows below the board: a remark, the status and the key bindings.
const ROWS_BELOW_BOARD: u16 = 3;

/// The number of rows the interface needs besides the board itself.
const ROWS_AROUND_BOARD: u16 = ROWS_ABOVE_BOARD + ROWS_BELOW_BOARD;

/// The place of every part of the interface.
///
/// All parts share the same horizontal centre, so the title, the board and the text below it line
/// up with each other.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Geometry {
    dimensions: BoardDimensions,
    scale: Scale,
    /// The whole interface, centred inside the area it was given.
    pub content: Rect,
    /// The title.
    pub title: Rect,
    /// The line that names the opponent.
    pub subtitle: Rect,
    /// The row that marks the selected column.
    pub indicator: Rect,
    /// The board, including its frame.
    pub board: Rect,
    /// The remark about the last action.
    pub notice: Rect,
    /// The line that says whose turn it is.
    pub status: Rect,
    /// The key bindings.
    pub help: Rect,
}

impl Geometry {
    /// The place of every part of an interface for a board of the given size, centred in an area.
    ///
    /// The board is drawn at the largest [`Scale`] that fits. Returns [`None`] when the area is
    /// smaller than [`required_size`].
    pub fn new(area: Rect, dimensions: BoardDimensions) -> Option<Self> {
        Scale::ALL
            .into_iter()
            .rev()
            .find_map(|scale| Self::at_scale(area, dimensions, scale))
    }

    /// The place of every part of an interface drawn at one scale, centred in an area.
    ///
    /// Returns [`None`] when the area is smaller than [`required_size_at`] that scale.
    pub fn at_scale(area: Rect, dimensions: BoardDimensions, scale: Scale) -> Option<Self> {
        let (width, height) = required_size_at(dimensions, scale);
        if area.width < width || area.height < height {
            return None;
        }

        let content = Rect {
            x: area.x + (area.width - width) / 2,
            y: area.y + (area.height - height) / 2,
            width,
            height,
        };

        let board = centred_board(content, dimensions, scale);

        Some(Self {
            dimensions,
            scale,
            content,
            title: line(content, 0),
            subtitle: line(content, 1),
            indicator: line(content, ROWS_ABOVE_BOARD - 1),
            board,
            notice: line(content, ROWS_ABOVE_BOARD + board.height),
            status: line(content, ROWS_ABOVE_BOARD + board.height + 1),
            help: line(content, ROWS_ABOVE_BOARD + board.height + 2),
        })
    }

    /// The size of the board the geometry was made for.
    pub const fn dimensions(&self) -> BoardDimensions {
        self.dimensions
    }

    /// How big the board is drawn.
    pub const fn scale(&self) -> Scale {
        self.scale
    }

    /// The place of one slot of the board.
    ///
    /// Cells outside the board have no place on the screen.
    pub fn cell(&self, cell: Cell) -> Option<Rect> {
        let is_on_board =
            cell.column < self.dimensions.column_count() && cell.row < self.dimensions.row_count();
        if !is_on_board {
            return None;
        }

        let column = u16::try_from(cell.column).ok()?;
        let rows_from_top = u16::try_from(self.dimensions.row_count() - 1 - cell.row).ok()?;

        Some(Rect {
            x: self.board.x + 1 + column * self.scale.cell_width(),
            y: self.board.y + 1 + rows_from_top * self.scale.cell_height(),
            width: self.scale.cell_width(),
            height: self.scale.cell_height(),
        })
    }

    /// The screen column that runs through the middle of a column of the board.
    pub fn column_middle(&self, column: usize) -> Option<u16> {
        let cell = self.cell(Cell::new(column, 0))?;
        Some(cell.x + self.scale.cell_width() / 2)
    }
}

/// The smallest area an interface for a board of the given size fits in.
pub fn required_size(dimensions: BoardDimensions) -> (u16, u16) {
    required_size_at(dimensions, Scale::default())
}

/// The smallest area an interface drawn at one scale fits in.
pub fn required_size_at(dimensions: BoardDimensions, scale: Scale) -> (u16, u16) {
    let (board_width, board_height) = board_size(dimensions, scale);
    let width = board_width
        .max(text_width(HELP))
        .max(text_width(TITLE))
        .max(widest(&opponent_text));

    (width, board_height + ROWS_AROUND_BOARD)
}

/// The line the game shows to name the opponent.
pub fn opponent_text(difficulty: Difficulty) -> String {
    format!("vs {difficulty}")
}

/// The width of the longest line a level can produce.
fn widest(text_of: &dyn Fn(Difficulty) -> String) -> u16 {
    Difficulty::ALL
        .into_iter()
        .map(|difficulty| text_width(&text_of(difficulty)))
        .max()
        .unwrap_or_default()
}

/// The size of the board, including its frame.
fn board_size(dimensions: BoardDimensions, scale: Scale) -> (u16, u16) {
    (
        side_length(dimensions.column_count(), scale.cell_width()),
        side_length(dimensions.row_count(), scale.cell_height()),
    )
}

/// The length of one side of the board, from a number of slots and the size of a slot.
///
/// The two extra rows or columns are the frame around the board.
fn side_length(slot_count: usize, slot_size: u16) -> u16 {
    u16::try_from(slot_count)
        .unwrap_or(u16::MAX)
        .saturating_mul(slot_size)
        .saturating_add(2)
}

/// The board, centred in the interface and below the row that marks the selected column.
fn centred_board(content: Rect, dimensions: BoardDimensions, scale: Scale) -> Rect {
    let (width, height) = board_size(dimensions, scale);

    Rect {
        x: content.x + content.width.saturating_sub(width) / 2,
        y: content.y + ROWS_ABOVE_BOARD,
        width,
        height,
    }
}

fn text_width(text: &str) -> u16 {
    u16::try_from(text.chars().count()).unwrap_or(u16::MAX)
}

fn line(content: Rect, offset: u16) -> Rect {
    Rect {
        x: content.x,
        y: content.y + offset,
        width: content.width,
        height: 1,
    }
}