Skip to content

Grids

Two builders lay out a board. button_grid() makes a board of buttons people click, and emoji_grid() draws a board in text, one emoji per cell, that the view changes as play goes on.

This board marks each cell the first time someone clicks it:

from functools import partial

import discord

from cascadeui import StatefulButton, StatefulLayoutView, button_grid, card

EMPTY = "\N{BRAILLE PATTERN BLANK}"
MARK = "\N{HEAVY MULTIPLICATION X}"


class Board(StatefulLayoutView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.cells = [[EMPTY] * 3 for _ in range(3)]
        self.build_ui()

    def build_ui(self):
        self.clear_items()
        marked = sum(cell != EMPTY for row in self.cells for cell in row)
        self.add_item(card("## Board", f"-# {marked} of 9 marked", *button_grid(3, 3, self.cell)))

    def cell(self, row, col):  # (1)!
        mark = self.cells[row][col]
        return StatefulButton(
            label=mark,
            style=discord.ButtonStyle.primary if mark != EMPTY else discord.ButtonStyle.secondary,
            disabled=mark != EMPTY,
            callback=partial(self.mark, row, col),
        )

    async def mark(self, row, col, interaction):  # (2)!
        self.cells[row][col] = MARK
        self.build_ui()
        await self.refresh()
  1. Called once for each cell, with its row and column, to make that cell's button.
  2. partial passes the cell first, so the interaction comes last.

Animation: Kael uses /board and the Board card shows nine blank buttons under a 0 of 9 marked line, with self.cells beside it, every entry EMPTY. Kael clicks the middle cell: mark(1, 1) stores MARK and redraws in one request, so the cell turns blue with a cross, is disabled, and the line reads 1 of 9 marked. Kael clicks the top-right cell and mark(0, 2) does the same: partial gave the callback its cell, and the click came last

A Board of Buttons

button_grid(rows, cols, cell_factory) calls cell_factory(row, col) for every cell, top row first, and returns the rows of buttons as a list of action rows. Spread the list into a card, as above, or add each row to the view.

Kael uses /board and the Board card shows a three-by-three grid of blank buttons under a 0 of 9 marked line

  • Every cell is a button. A factory that returns anything else raises TypeError naming the cell. Give an empty cell a blank label, as the board above does with EMPTY: Discord refuses a button with neither a label nor an emoji.
  • A row holds up to five buttons, so cols runs from 1 to 5.
  • A message holds 40 components, and each grid row counts as its action row plus its buttons, so rows runs to 6 for five columns, 8 for four, or 20 for one. The rest of the panel counts toward the same 40: a five-by-five board in a card with a heading takes 32.

Each button gets its own id from its callback, the values the callback carries, and its label, so the cells stay apart. A cell whose label changes, as the board's do when they are marked, gets a new id, and a click sent from the board before is dropped and the board drawn again. See Generated Ids.

A Pick Board

A cell can show anything a button can, so a board can hide something under each cell. This chest gives three picks, and each pick opens its cell to show the prize:

from functools import partial

import discord

from cascadeui import StatefulButton, StatefulLayoutView, button_grid, card, divider

COIN, GEM, KEY = "\N{COIN}", "\N{GEM STONE}", "\N{KEY}"
PRIZES = [
    [(COIN, 50, "coins"), (GEM, 1, "gem"), (GEM, 2, "gems")],
    [(KEY, 1, "key"), (COIN, 100, "coins"), (GEM, 2, "gems")],
    [(COIN, 30, "coins"), (KEY, 2, "keys"), (COIN, 10, "coins")],
]
PICKS = 3


class Chest(StatefulLayoutView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.opened = []
        self.build_ui()

    def build_ui(self):
        self.clear_items()
        left = PICKS - len(self.opened)
        prizes = (PRIZES[row][col] for row, col in self.opened)
        found = " · ".join(f"{emoji} {count} {noun}" for emoji, count, noun in prizes)
        self.add_item(
            card(
                "## Daily Chest",
                "-# Three picks a day",
                divider(),
                f"Pick {left} more!" if left else "That's all for today!",
                *button_grid(3, 3, self.cell),
                divider(),
                f"**Rewards:** {found or 'nothing yet'}",
            )
        )

    def cell(self, row, col):
        if (row, col) in self.opened:  # (1)!
            emoji, count, _ = PRIZES[row][col]
            return StatefulButton(
                label=str(count), emoji=emoji, style=discord.ButtonStyle.success, disabled=True
            )
        return StatefulButton(
            label="?",
            disabled=len(self.opened) == PICKS,  # (2)!
            callback=partial(self.pick, row, col),
        )

    async def pick(self, row, col, interaction):
        self.opened.append((row, col))
        self.build_ui()
        await self.refresh()
  1. An opened cell shows its prize, an emoji and a number, on a green button that cannot be clicked again.
  2. Once the picks run out, every closed cell is disabled as well.

Animation: Kael uses /daily_chest and the Daily Chest card shows nine ? buttons under a Pick 3 more! line, with self.opened beside it, empty. Kael picks the middle cell: pick(1, 1) adds it to self.opened and redraws in one request, so the cell turns green with a coin and 100, the line reads Pick 2 more!, and the rewards line lists 100 coins. Kael picks the top-right cell, 2 gems, and then the bottom-middle cell, 2 keys: the line reads That's all for today! and the six closed cells grey out

The whole board comes from one list, self.opened: the line under the heading, every cell, and the rewards line. pick() never checks how many picks are left. Two clicks sent together on the last pick take turns, and when the second one's turn comes its cell is disabled, so it runs nothing (see Clicks Take Turns).

The picks live on the view, so each /daily_chest opens a new chest. A bot that allows one chest a day keeps the picks where they last, such as scoped state.

A Board Drawn in Text

emoji_grid(rows, cols) returns an EmojiGrid, a text display that draws one emoji per cell and rewrites its own text whenever a cell changes. It goes anywhere a text display goes, a card included:

from cascadeui import card, emoji_grid

grid = emoji_grid(3, 3, fill="⬜", row_labels="numeric", col_labels="alpha")
grid[0, 0] = "❌"
grid[1, 1] = "⭕"
grid[2, 2] = "❌"
self.add_item(card("## Board", grid))

The Board card drawing a three-by-three grid of white squares, A B C over the columns and 1 2 3 before the rows, a white square in the corner, crosses at A1 and C3 and a nought at B2

fill is what every cell starts as, a black square unless you give another. The whole board is one component however many cells it has, so a ten-by-ten board fits where a board of buttons cannot. People cannot click its cells: pair it with buttons or selects that change it, as v2_battleship.py does.

Setting Cells

A cell is named by its row and column, counting from 0, or by its place in reading order (row * cols + col):

To Write
Set one cell grid[2, 3] = "🔥", or grid[13] = "🔥" on a five-column board
Set several cells grid[[(0, 0), (1, 1)]] = "⭐"
Fill a rectangle, corners included grid.fill_rect((0, 0), (1, 2), "🟦")
Put every cell back to fill grid.clear()
Read a cell grid[2, 3]

Several cells go in a list: a tuple of two numbers is always one cell. fill_rect() takes either form for each corner. A cell outside the board raises IndexError, and a value that is not text raises TypeError. grid.rows and grid.cols give the board's size.

Animation: a four-by-five board of white squares beside the four lines, run in turn. grid[2, 3] puts a fire in row 2, column 3, counting from 0, the same cell as grid[13] (2 * 5 + 3). grid[[(0, 0), (1, 1)]] puts a star in two cells. grid.fill_rect((0, 0), (1, 2), ...) turns the first three cells of the top two rows blue, covering the stars and leaving the fire. grid.clear() puts every cell back to white

Labels

row_labels puts a label before each row and col_labels a header above the columns. Each takes:

  • "alpha": the letters A to Z as emoji, for up to 26 rows or columns
  • "numeric": the keycap numbers 1 to 10, for up to 10
  • a list of labels, one for each row or column, for anything else
  • None, the default: no labels on that side.

With both, the cell where the header meets the label column shows corner, which is fill unless you give another.

Four small boards of white squares. col_labels="alpha" puts A B C D over the columns. row_labels="numeric" puts 1 2 3 before the rows. A list puts a dog, a cat, and a mouse before the rows, one label each. With both labels, corner puts a target where the header meets the label column

Keeping the Board on Screen

Changing a cell changes the grid's text right away, but nothing reaches Discord until the view sends it. A callback that changes cells calls refresh():

import random

from cascadeui import StatefulLayoutView, button_row, card, emoji_grid


class Target(StatefulLayoutView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.board = emoji_grid(5, 5, fill="🟦", row_labels="alpha", col_labels="numeric")
        self.add_item(card("## Target", self.board))
        self.add_item(button_row({"Fire": self.fire}))

    async def fire(self, interaction):
        self.board[random.randrange(25)] = "💥"
        await self.refresh()  # (1)!
  1. The grid has already rewritten its text, so the view has nothing to rebuild.

Animation: Kael uses /target and the Target card shows a five-by-five board of blue squares, 1 to 5 over the columns and A to E before the rows. Kael clicks Fire: random.randrange(25) gives 19, and fire() writes an explosion into self.board[19], row 3, column 4, the cell in row D under 5. The grid rewrote its own text, so refresh() sends it. Kael clicks Fire again: 8 this time, row B under 4, in one request again, and the first shot stays, since the grid is the board's record

This view keeps one grid and changes it: the grid is the board's record. When the record lives somewhere else (a game object, a database), build a new grid from it in build_ui() each time instead, so the board on screen always matches the record.

Size Limits

The text of a text display is capped at 4000 characters. emoji_grid() raises ValueError when a board's first drawing is over that, and a board that grows past it later, by writing longer values into cells, is refused at its next send or edit (see What Is Checked). A ten-by-ten board with both labels is about 260 characters, so the cap leaves room for large boards. The whole message's text is capped at 4000 too, so two big boards and their headings share one budget.

Less common cases

No space between cells. cell_sep is what goes between cells, a space unless you give another. Two letter emoji that touch show as a flag (C and D make the Congo's), so with cell_sep="" a zero-width space goes between any two that would touch.

Two one-row boards built with emoji_grid(1, 4, col_labels="alpha", cell_sep=""): as built, a zero-width space sits between each pair of letters, so no two touch. With those spaces taken out, C and D touch and show as one flag, the Congo's

A panel that survives a restart. Its buttons need a custom_id each: give every cell one built from its place, such as custom_id=f"cell:{row}:{col}". See A Panel That Comes Back.

The Board panel with the middle and top-right cells marked in blue, beside each cell's custom_id, cell:0:0 to cell:2:2, built from the cell's place with custom_id=f"cell:{row}:{col}", so it is the same after a restart

Refused when built.

  • a rows or cols that is not a whole number of at least 1 (a bool included)
  • more than five columns, or too many rows for 40 components, in button_grid()
  • a label preset other than "alpha" or "numeric", or a preset with more rows or columns than it has labels
  • a list of labels of the wrong length, or with an entry that is not text
  • a corner given without both labels