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()
- Called once for each cell, with its row and column, to make that cell's button.
partialpasses the cell first, so the interaction comes 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.
- Every cell is a button. A factory that returns anything else raises
TypeErrornaming the cell. Give an empty cell a blank label, as the board above does withEMPTY: Discord refuses a button with neither a label nor an emoji. - A row holds up to five buttons, so
colsruns from 1 to 5. - A message holds 40 components, and each grid row counts as its action row plus its buttons, so
rowsruns 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()
- An opened cell shows its prize, an emoji and a number, on a green button that cannot be clicked again.
- Once the picks run out, every closed cell is disabled as well.
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))
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.
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.
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)!
- The grid has already rewritten its text, so the view has nothing to rebuild.
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.
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.
Refused when built.
- a
rowsorcolsthat is not a whole number of at least 1 (aboolincluded) - 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
cornergiven without both labels
Related¶
- Choice and Toggle Controls: a single row of buttons with
button_row(). - Passing Context to Callbacks:
partialand the cell a button stands for. - Layout Rules and Limits: counting a panel's components.
emoji_grid()andbutton_grid(): every parameter.