fours 0.1.0

Four in a row in your terminal, with three levels of opponent.
Documentation
//! Drawing the interface.

use crate::app::App;
use crate::app::Headline;
use crate::app::Theme;
use crate::app::layout;
use crate::app::layout::Geometry;
use crate::app::layout::Scale;
use crate::game::BoardDimensions;
use crate::game::Cell;
use crate::game::GameState;
use crate::game::Player;
use crate::game::Status;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Color;
use ratatui::style::Modifier;
use ratatui::style::Style;
use ratatui::text::Text;
use ratatui::widgets::Block;
use ratatui::widgets::BorderType;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
use ratatui::widgets::Wrap;

/// The rows a disc is drawn with, from its top down, at each [`Scale`].
///
/// Half a slot is cut from each corner so that a stack of discs in one colour can still be
/// counted: the sides of the discs part company where they meet.
const SMALL_DISC: [&str; 2] = ["▄█▄", "▀█▀"];
const LARGE_DISC: [&str; 3] = ["▄███▄", "█████", "▀███▀"];

/// The mark above the selected column.
const SELECTION_MARK: &str = "▼";

/// Draw the whole interface into an area.
pub fn render(app: &App, theme: &Theme, area: Rect, buffer: &mut Buffer) {
    buffer.set_style(area, Style::new().bg(theme.background).fg(theme.text));

    let Some(geometry) = Geometry::new(area, app.state().dimensions()) else {
        render_too_small(app.state().dimensions(), theme, area, buffer);
        return;
    };

    render_line(layout::TITLE, title_style(theme), geometry.title, buffer);
    render_line(
        layout::opponent_text(app.difficulty()),
        Style::new().fg(theme.muted),
        geometry.subtitle,
        buffer,
    );

    render_indicator(app, theme, &geometry, buffer);
    render_board(app, theme, &geometry, buffer);

    if let Some(notice) = app.notice() {
        let style = Style::new().fg(theme.notice);
        render_line(notice.message(), style, geometry.notice, buffer);
    }

    let status = status_style(app, theme);
    render_line(app.headline_text(), status, geometry.status, buffer);
    render_line(
        layout::HELP,
        Style::new().fg(theme.muted),
        geometry.help,
        buffer,
    );
}

/// The look of the title above the board.
fn title_style(theme: &Theme) -> Style {
    Style::new().fg(theme.title).add_modifier(Modifier::BOLD)
}

/// Draw one line of text in the middle of an area.
fn render_line<'a>(text: impl Into<Text<'a>>, style: Style, area: Rect, buffer: &mut Buffer) {
    Paragraph::new(text)
        .style(style)
        .centered()
        .render(area, buffer);
}

/// The colour of the line that says whose turn it is, or who won.
fn status_style(app: &App, theme: &Theme) -> Style {
    let headline = app.headline();
    let colour = headline
        .player()
        .map_or(theme.text, |player| theme.disc(player));

    match headline {
        Headline::Won(_) => Style::new().fg(colour).add_modifier(Modifier::BOLD),
        Headline::Turn(_) | Headline::Draw => Style::new().fg(colour),
    }
}

fn render_indicator(app: &App, theme: &Theme, geometry: &Geometry, buffer: &mut Buffer) {
    if !app.is_waiting_for_player() {
        return;
    }

    let Some(middle) = geometry.column_middle(app.selected_column()) else {
        return;
    };

    let style = Style::new()
        .fg(theme.disc(app.state().current_player()))
        .add_modifier(Modifier::BOLD);

    buffer.set_string(middle, geometry.indicator.y, SELECTION_MARK, style);
}

fn render_board(app: &App, theme: &Theme, geometry: &Geometry, buffer: &mut Buffer) {
    Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(Style::new().fg(theme.board_border).bg(theme.background))
        .style(Style::new().bg(theme.board))
        .render(geometry.board, buffer);

    let view = BoardView::of(app, theme, geometry);
    for row in 0..view.state.row_count() {
        for column in 0..view.state.column_count() {
            view.render_slot(Cell::new(column, row), buffer);
        }
    }
}

/// What the board looks like for one frame.
///
/// The answers that hold for the whole board, such as where a placed disc would land, are worked
/// out once here rather than once for every slot.
struct BoardView<'a> {
    state: &'a GameState,
    theme: &'a Theme,
    geometry: &'a Geometry,
    human_player: Player,
    /// The column the player is pointing at, while the player may place a disc.
    selected_column: Option<usize>,
    /// Where a placed disc would land, while the player may place one.
    preview: Option<Cell>,
    /// The discs that won the game, empty while the game is still being played.
    winning_line: &'a [Cell],
}

impl<'a> BoardView<'a> {
    fn of(app: &'a App, theme: &'a Theme, geometry: &'a Geometry) -> Self {
        let state = app.state();
        let selected_column = app.is_waiting_for_player().then(|| app.selected_column());

        Self {
            state,
            theme,
            geometry,
            human_player: app.human_player(),
            selected_column,
            preview: selected_column.and_then(|column| state.landing_cell(column)),
            winning_line: match state.status() {
                Status::Won(victory) => victory.line(),
                Status::InProgress | Status::Draw => &[],
            },
        }
    }

    fn render_slot(&self, cell: Cell, buffer: &mut Buffer) {
        let Some(area) = self.geometry.cell(cell) else {
            return;
        };

        let background = self.background(cell.column);
        let disc = self.disc_look(cell);
        let style = Style::new()
            .fg(disc.colour)
            .bg(background)
            .add_modifier(disc.emphasis);

        buffer.set_style(area, Style::new().bg(background));
        for (offset, shape) in disc_shape(self.geometry.scale()).iter().enumerate() {
            let row = u16::try_from(offset).unwrap_or_default();
            buffer.set_string(area.x + 1, area.y + row, shape, style);
        }
    }

    fn background(&self, column: usize) -> Color {
        if self.selected_column == Some(column) {
            self.theme.board_highlight
        } else {
            self.theme.board
        }
    }

    /// How the disc of a slot should look.
    ///
    /// A slot that holds a disc shows it, and steps back once another line has won the game. An
    /// empty slot shows a hole, or a faint preview of the disc that would land there.
    fn disc_look(&self, cell: Cell) -> DiscLook {
        match self.state.piece_at(cell) {
            Some(player) if self.is_faded(cell) => DiscLook::faint(self.theme.disc(player)),
            Some(player) => DiscLook::solid(self.theme.disc(player)),
            None if self.preview == Some(cell) => {
                DiscLook::faint(self.theme.disc(self.human_player))
            }
            None => DiscLook::solid(self.theme.hole),
        }
    }

    /// Whether a disc should step back so that a winning line stands out.
    fn is_faded(&self, cell: Cell) -> bool {
        !self.winning_line.is_empty() && !self.winning_line.contains(&cell)
    }
}

/// The rows a disc is drawn with at a scale.
fn disc_shape(scale: Scale) -> &'static [&'static str] {
    match scale {
        Scale::Normal => &SMALL_DISC,
        Scale::Large => &LARGE_DISC,
    }
}

/// How the disc of a slot is drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DiscLook {
    colour: Color,
    emphasis: Modifier,
}

impl DiscLook {
    const fn solid(colour: Color) -> Self {
        Self {
            colour,
            emphasis: Modifier::empty(),
        }
    }

    const fn faint(colour: Color) -> Self {
        Self {
            colour,
            emphasis: Modifier::DIM,
        }
    }
}

/// The message shown when the terminal is too small to hold the board.
fn render_too_small(dimensions: BoardDimensions, theme: &Theme, area: Rect, buffer: &mut Buffer) {
    let (width, height) = layout::required_size(dimensions);
    render_message(&too_small_message(width, height), theme, area, buffer);
}

fn too_small_message(width: u16, height: u16) -> String {
    format!("Terminal too small, the game needs {width} by {height}.")
}

/// Draw a message in the middle of an area, wrapping it if it does not fit on one line.
fn render_message(message: &str, theme: &Theme, area: Rect, buffer: &mut Buffer) {
    let target = middle_of(area, wrapped_height(message, area));

    Paragraph::new(message.to_owned())
        .style(Style::new().fg(theme.notice))
        .wrap(Wrap { trim: true })
        .centered()
        .render(target, buffer);
}

/// About how many rows a message needs once it is wrapped to the width of an area.
///
/// Wrapping happens between words, so this can come out a row short for a long message in a narrow
/// terminal. It only places the message, which stays readable either way.
fn wrapped_height(message: &str, area: Rect) -> u16 {
    let width = usize::from(area.width.max(1));
    let rows = u16::try_from(message.chars().count().div_ceil(width)).unwrap_or(u16::MAX);

    rows.clamp(1, area.height.max(1))
}

/// A strip of the given height in the middle of an area.
fn middle_of(area: Rect, height: u16) -> Rect {
    Rect {
        x: area.x,
        y: area.y + area.height.saturating_sub(height) / 2,
        width: area.width,
        height,
    }
}