Build chess between two members as a /chess command with subcommands, each game being one Components V2 card updated in place after every move. /chess play challenges someone. The card is a container: a heading with both players, the board as one full-width picture (a gallery, not a thumbnail) composed from a set of twelve piece sprites you make with the image model, then whose turn it is, a check warning, the pieces each side has taken, the last move and the recent move list, then a two-step move input: a select menu of the pieces of the side to move that have at least one move, and once one is picked the card is rewritten with a menu of that piece's squares, each marked with what it takes and whether it gives check, plus a Back button; a Resign button is always there. Only the player to move can use the menus; others get a private explanation. Keep /chess move from one square to another in algebraic notation like e2 to e4 as a typed alternative, with an optional promotion piece. Pieces move and capture as in chess without castling or en passant, a pawn reaching the last rank becomes the piece picked (a queen by default), capturing the king wins, and /chess resign gives up. A setting chooses between rewriting one card and posting a new card after every move.
A two-player chess game on one card that updates after every move. Challenge someone with /chess play @opponent: the card shows both players, the board as one large picture with coordinates on all sides, whose turn it is, a warning when a king is in check, the pieces each side has taken, the last move and the move list. To move, pick one of your pieces in the menu under the board (only pieces that can move are listed), then pick its square in the second menu, which marks captures and checks; Back returns to the pieces, and only the player to move can use them. Typing /chess move e2 e4 still works, and /chess resign or the Resign button gives up. A pawn reaching the last rank becomes the piece you pick (a queen by default), and capturing the king wins the game.
Made by MEE6. Remix it to get a copy of your own and change anything you like.
⚪ @You vs ⚫ @Jordan
👑 @You took the king and wins! White has taken ♟ · Black has taken —
Last move: ♕ f7-e8, took ♚ King Moves: 1. e2-e4 e7-e5 2. f1-c4 b8-c6 3. d1-h5 g8-f6 4. h5-f7 a7-a6 5. f7-e8
// Chess game between two players: one card per game, moves picked in menus or typed
interface ChessGame {
white: string; // user id
black: string; // user id
board: string[][]; // 8x8 grid of piece names (e.g. 'king_w', 'pawn_b', '')
turn: 'white' | 'black';
lastMove?: string;
boardChannelId: string; // where the board message lives
boardMessageId: string; // the board message to edit
moves: string[]; // list of moves in notation (e.g. 'e2-e4')
moveNumber: number; // current move number
/** the piece the last move took, e.g. 'pawn_b' — absent when it took nothing */
lastCapture?: string;
}
// A game lasts as long as the players come back to it within this many seconds.
const GAME_TTL = 86400;
const BROWN = 0xb58863;
const PIECE_NAMES: Record<string, string> = {
king: 'King',
queen: 'Queen',
rook: 'Rook',
bishop: 'Bishop',
knight: 'Knight',
pawn: 'Pawn',
};
const SYMBOLS: Record<string, string> = {
king_w: '♔',
queen_w: '♕',
rook_w: '♖',
bishop_w: '♗',
knight_w: '♘',
pawn_w: '♙',
king_b: '♚',
queen_b: '♛',
rook_b: '♜',
bishop_b: '♝',
knight_b: '♞',
pawn_b: '♟',
};
// The order pieces are listed in the menu, and how many of each a side starts with
const PIECE_ORDER = ['king', 'queen', 'rook', 'bishop', 'knight', 'pawn'];
const START_COUNT: Record<string, number> = { king: 1, queen: 1, rook: 2, bishop: 2, knight: 2, pawn: 8 };
const PROMOTIONS = ['queen', 'rook', 'bishop', 'knight'];
// Initialize a standard chess board
function initBoard(): string[][] {
return [
['rook_b', 'knight_b', 'bishop_b', 'queen_b', 'king_b', 'bishop_b', 'knight_b', 'rook_b'],
['pawn_b', 'pawn_b', 'pawn_b', 'pawn_b', 'pawn_b', 'pawn_b', 'pawn_b', 'pawn_b'],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['pawn_w', 'pawn_w', 'pawn_w', 'pawn_w', 'pawn_w', 'pawn_w', 'pawn_w', 'pawn_w'],
['rook_w', 'knight_w', 'bishop_w', 'queen_w', 'king_w', 'bishop_w', 'knight_w', 'rook_w'],
];
}
// Convert algebraic notation (e.g. 'e2') to [row, col]
function parseSquare(square: string): [number, number] | null {
if (square.length !== 2) return null;
const col = square.charCodeAt(0) - 97; // 'a' = 0, 'b' = 1, etc.
const row = 8 - parseInt(square[1]); // '8' = row 0, '1' = row 7
if (col < 0 || col > 7 || row < 0 || row > 7 || isNaN(row)) return null;
return [row, col];
}
// Convert [row, col] to algebraic notation
function toAlgebraic(row: number, col: number): string {
return String.fromCharCode(97 + col) + (8 - row);
}
// Get piece color from piece name
function pieceColor(piece: string): 'white' | 'black' | null {
if (!piece) return null;
return piece.endsWith('_w') ? 'white' : 'black';
}
// Get piece type from piece name
function pieceType(piece: string): string {
if (!piece) return '';
return piece.split('_')[0];
}
function opposite(color: 'white' | 'black'): 'white' | 'black' {
return color === 'white' ? 'black' : 'white';
}
/** "♘ Knight" */
function pieceLabel(piece: string): string {
return `${SYMBOLS[piece] ?? ''} ${PIECE_NAMES[pieceType(piece)] ?? ''}`.trim();
}
// Check if a move is valid (basic rules, no check detection)
function isValidMove(game: ChessGame, from: [number, number], to: [number, number]): boolean {
const [fromRow, fromCol] = from;
const [toRow, toCol] = to;
const piece = game.board[fromRow][fromCol];
const target = game.board[toRow][toCol];
// Must move your own piece
if (pieceColor(piece) !== game.turn) return false;
// Cannot capture your own piece
if (target && pieceColor(target) === game.turn) return false;
const type = pieceType(piece);
const rowDiff = toRow - fromRow;
const colDiff = toCol - fromCol;
const absRowDiff = Math.abs(rowDiff);
const absColDiff = Math.abs(colDiff);
// Pawn moves
if (type === 'pawn') {
const direction = game.turn === 'white' ? -1 : 1; // white moves up (negative), black moves down (positive)
const startRow = game.turn === 'white' ? 6 : 1;
// Forward move
if (colDiff === 0 && !target) {
if (rowDiff === direction) return true;
if (fromRow === startRow && rowDiff === 2 * direction && !game.board[fromRow + direction][fromCol]) return true;
}
// Diagonal capture
if (absColDiff === 1 && rowDiff === direction && target) return true;
return false;
}
// Rook moves
if (type === 'rook') {
if (rowDiff === 0 || colDiff === 0) {
return !isPathBlocked(game.board, from, to);
}
return false;
}
// Knight moves
if (type === 'knight') {
return (absRowDiff === 2 && absColDiff === 1) || (absRowDiff === 1 && absColDiff === 2);
}
// Bishop moves
if (type === 'bishop') {
if (absRowDiff === absColDiff && absRowDiff > 0) {
return !isPathBlocked(game.board, from, to);
}
return false;
}
// Queen moves (rook + bishop)
if (type === 'queen') {
if (rowDiff === 0 || colDiff === 0 || absRowDiff === absColDiff) {
return !isPathBlocked(game.board, from, to);
}
return false;
}
// King moves
if (type === 'king') {
return absRowDiff <= 1 && absColDiff <= 1 && (absRowDiff > 0 || absColDiff > 0);
}
return false;
}
// Check if path between two squares is blocked (for rook, bishop, queen)
function isPathBlocked(board: string[][], from: [number, number], to: [number, number]): boolean {
const [fromRow, fromCol] = from;
const [toRow, toCol] = to;
const rowStep = toRow === fromRow ? 0 : (toRow - fromRow) / Math.abs(toRow - fromRow);
const colStep = toCol === fromCol ? 0 : (toCol - fromCol) / Math.abs(toCol - fromCol);
let row = fromRow + rowStep;
let col = fromCol + colStep;
while (row !== toRow || col !== toCol) {
if (board[row][col]) return true;
row += rowStep;
col += colStep;
}
return false;
}
// Find the king of a given color
function findKing(board: string[][], color: 'white' | 'black'): [number, number] | null {
const kingPiece = color === 'white' ? 'king_w' : 'king_b';
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
if (board[row][col] === kingPiece) return [row, col];
}
}
return null;
}
/** Whether a piece of `by` could move onto `square` */
function isAttacked(board: string[][], square: [number, number], by: 'white' | 'black'): boolean {
const probe = { board, turn: by } as ChessGame;
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
if (pieceColor(board[row][col]) === by && isValidMove(probe, [row, col], square)) return true;
}
}
return false;
}
/** Whether `color`'s king is attacked — a check */
function inCheck(board: string[][], color: 'white' | 'black'): boolean {
const king = findKing(board, color);
return king ? isAttacked(board, king, opposite(color)) : false;
}
/** Every square the piece on `from` can move to, for the side to move */
function movesFrom(game: ChessGame, from: [number, number]): [number, number][] {
const out: [number, number][] = [];
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
if (isValidMove(game, from, [row, col])) out.push([row, col]);
}
}
return out;
}
/** Whether a pawn moving to `to` reaches the last rank */
function promotes(game: ChessGame, from: [number, number], to: [number, number]): boolean {
return pieceType(game.board[from[0]][from[1]]) === 'pawn' && (to[0] === 0 || to[0] === 7);
}
// Execute a move
function executeMove(game: ChessGame, from: [number, number], to: [number, number], promotion = 'queen'): void {
const [fromRow, fromCol] = from;
const [toRow, toCol] = to;
const piece = game.board[fromRow][fromCol];
const target = game.board[toRow][toCol];
// Move the piece
game.board[toRow][toCol] = piece;
game.board[fromRow][fromCol] = '';
// Pawn promotion: a queen unless the player picked another piece
let promoted = '';
if (pieceType(piece) === 'pawn') {
if ((game.turn === 'white' && toRow === 0) || (game.turn === 'black' && toRow === 7)) {
const type = PROMOTIONS.includes(promotion) ? promotion : 'queen';
game.board[toRow][toCol] = `${type}_${game.turn === 'white' ? 'w' : 'b'}`;
promoted = `=${type === 'knight' ? 'N' : type[0].toUpperCase()}`;
}
}
// Record move in notation
const moveNotation = `${toAlgebraic(fromRow, fromCol)}-${toAlgebraic(toRow, toCol)}${promoted}`;
game.moves.push(moveNotation);
game.lastMove = moveNotation;
if (target) game.lastCapture = target;
else delete game.lastCapture;
// Switch turn (increment move number when black finishes their turn)
if (game.turn === 'black') {
game.moveNumber++;
}
game.turn = game.turn === 'white' ? 'black' : 'white';
}
/** What a move would do, for the menu: take a piece, give check, win, or leave the king open */
function moveNote(game: ChessGame, from: [number, number], to: [number, number], promotion = 'queen'): string {
const target = game.board[to[0]][to[1]];
if (pieceType(target) === 'king') return 'Takes the king and wins!';
const after: ChessGame = { ...game, board: game.board.map((row) => row.slice()), moves: [] };
executeMove(after, from, to, promotion);
const notes: string[] = [];
if (target) notes.push(`Takes the ${pieceLabel(target)}`);
if (inCheck(after.board, after.turn)) notes.push('Check!');
if (inCheck(after.board, game.turn)) notes.push('Leaves your king open');
return notes.join(' · ') || 'Quiet move';
}
/** The pieces each side has lost, worked out from the board (a promoted pawn is not counted as taken) */
function takenFrom(board: string[][], color: 'white' | 'black'): string[] {
const suffix = color === 'white' ? '_w' : '_b';
const count: Record<string, number> = {};
for (const row of board)
for (const cell of row) if (cell.endsWith(suffix)) count[pieceType(cell)] = (count[pieceType(cell)] ?? 0) + 1;
let promoted = 0;
const taken: string[] = [];
for (const type of ['queen', 'rook', 'bishop', 'knight']) {
const have = count[type] ?? 0;
promoted += Math.max(0, have - START_COUNT[type]);
for (let i = have; i < START_COUNT[type]; i++) taken.push(SYMBOLS[type + suffix]);
}
const pawns = 8 - (count.pawn ?? 0) - promoted;
for (let i = 0; i < pawns; i++) taken.push(SYMBOLS['pawn' + suffix]);
return taken;
}
// Format move history for display: the last ten moves
function formatMoveHistory(game: ChessGame): string {
if (game.moves.length === 0) return '';
const pairs: string[] = [];
for (let i = 0; i < game.moves.length; i += 2) {
const moveNum = Math.floor(i / 2) + 1;
const whiteMove = game.moves[i];
const blackMove = game.moves[i + 1] || '';
pairs.push(`${moveNum}. ${whiteMove}${blackMove ? ' ' + blackMove : ''}`);
}
const shown = pairs.slice(-10);
return `Moves: ${pairs.length > shown.length ? '… ' : ''}${shown.join(' ')}`;
}
// Draw the board
async function drawBoard(game: ChessGame): Promise<string> {
return await mee6.board({
cells: game.board,
cell: 64,
light: '#F0D9B5',
dark: '#B58863',
labels: {
top: 'abcdefgh',
bottom: 'abcdefgh',
left: '87654321',
right: '87654321',
},
});
}
// ---------------------------------------------------------------------------
// The card: one Components V2 message per game, rewritten after every move
// ---------------------------------------------------------------------------
function playerOf(game: ChessGame, color: 'white' | 'black'): string {
return color === 'white' ? game.white : game.black;
}
/** Whose turn and whether they are in check — or how the game ended — then what was taken and played */
function statusText(game: ChessGame, outcome?: string): string {
const lines: string[] = [];
if (outcome) {
lines.push(`### Game over\n${outcome}`);
} else {
const colour = game.turn === 'white' ? '⚪ White' : '⚫ Black';
lines.push(`**${colour} to move** — <@${playerOf(game, game.turn)}>`);
if (inCheck(game.board, game.turn)) {
lines.push(`⚠️ **Check!** The ${game.turn} king is attacked — save it, or it is taken.`);
}
}
const byWhite = takenFrom(game.board, 'black');
const byBlack = takenFrom(game.board, 'white');
if (byWhite.length || byBlack.length) {
lines.push(`White has taken ${byWhite.join('') || '—'} · Black has taken ${byBlack.join('') || '—'}`);
}
if (game.lastMove) {
const to = parseSquare(game.lastMove.slice(3, 5));
const piece = to ? game.board[to[0]][to[1]] : '';
const took = game.lastCapture ? `, took ${pieceLabel(game.lastCapture)}` : '';
lines.push(`-# Last move: ${piece ? SYMBOLS[piece] + ' ' : ''}${game.lastMove}${took}`);
}
const history = formatMoveHistory(game);
if (history) lines.push(`-# ${history}`);
return lines.join('\n');
}
/** Step one: the pieces of the side to move that have somewhere to go */
function pieceMenu(game: ChessGame): LayoutBlock {
const pieces: { piece: string; square: [number, number]; moves: [number, number][] }[] = [];
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const piece = game.board[row][col];
if (pieceColor(piece) !== game.turn) continue;
const moves = movesFrom(game, [row, col]);
if (moves.length) pieces.push({ piece, square: [row, col], moves });
}
}
pieces.sort(
(a, b) =>
PIECE_ORDER.indexOf(pieceType(a.piece)) - PIECE_ORDER.indexOf(pieceType(b.piece)) ||
a.square[1] - b.square[1] ||
b.square[0] - a.square[0]
);
const options = pieces.slice(0, 25).map(({ piece, square, moves }) => {
const takes = moves.some(([r, c]) => game.board[r][c]);
return {
label: `${pieceLabel(piece)} ${toAlgebraic(square[0], square[1])}`,
value: toAlgebraic(square[0], square[1]),
description: `${moves.length} move${moves.length === 1 ? '' : 's'}${takes ? ' · can take a piece' : ''}`,
};
});
return {
type: 'select',
select: {
customId: 'chess:piece',
placeholder: `${game.turn === 'white' ? 'White' : 'Black'}: pick a piece to move`,
options,
},
};
}
/** Step two: where the picked piece can go — a pawn on the last rank once per promotion piece */
function destinationMenus(game: ChessGame, from: [number, number]): LayoutBlock[] {
const piece = game.board[from[0]][from[1]];
const fromSquare = toAlgebraic(from[0], from[1]);
const options: { label: string; value: string; description: string }[] = [];
for (const to of movesFrom(game, from)) {
const square = toAlgebraic(to[0], to[1]);
if (promotes(game, from, to)) {
for (const type of PROMOTIONS) {
const letter = type === 'knight' ? 'N' : type[0].toUpperCase();
const into = `${type}_${game.turn === 'white' ? 'w' : 'b'}`;
options.push({
label: `${square}=${letter} — becomes a ${pieceLabel(into)}`,
value: `${square}=${type}`,
description: moveNote(game, from, to, type),
});
}
} else {
options.push({ label: `${fromSquare} → ${square}`, value: square, description: moveNote(game, from, to) });
}
}
// Winning moves first, then captures, then the rest square by square
const rank = (o: { description: string }) =>
o.description.startsWith('Takes the king') ? 0 : o.description.startsWith('Takes') ? 1 : 2;
options.sort((a, b) => rank(a) - rank(b) || a.value.slice(0, 2).localeCompare(b.value.slice(0, 2)));
const menus: LayoutBlock[] = [];
for (let i = 0; i < options.length; i += 25) {
menus.push({
type: 'select',
select: {
customId: `chess:to:${fromSquare}:${i / 25}`,
placeholder: `Move the ${pieceLabel(piece)} from ${fromSquare} to…`,
options: options.slice(i, i + 25),
},
});
}
return menus;
}
/**
* The game's card. `picked` shows step two, the destinations of that piece;
* `outcome` ends the game; `controls: false` leaves an earlier board without menus.
*/
async function panel(
game: ChessGame,
opts: { picked?: [number, number]; outcome?: string; controls?: boolean } = {}
): Promise<MessagePayload> {
const blocks: LayoutBlock[] = [
{ type: 'text', text: `## ♟️ Chess\n⚪ <@${game.white}> vs ⚫ <@${game.black}>` },
{ type: 'gallery', items: [await drawBoard(game)] },
{ type: 'text', text: statusText(game, opts.outcome) },
];
if (!opts.outcome && opts.controls !== false) {
const resign = { label: 'Resign', style: 'danger' as const, customId: 'chess:resign' };
if (opts.picked) {
blocks.push(...destinationMenus(game, opts.picked));
blocks.push({
type: 'buttons',
buttons: [{ label: 'Back', style: 'secondary', customId: 'chess:back' }, resign],
});
} else {
blocks.push(pieceMenu(game));
blocks.push({ type: 'buttons', buttons: [resign] });
}
}
return { layout: [{ type: 'container', color: BROWN, blocks }] };
}
/** Keep the game under its card's id, so the card's menus find it */
async function save(game: ChessGame, key: string): Promise<void> {
const current = `chess_${game.boardMessageId}`;
await mee6.store.set(current, game, { ttl: GAME_TTL });
if (key !== current) await mee6.store.delete(key);
}
/**
* Play a move and show it: rewrite the card, or post a new one under the
* "every_move" setting (the earlier card keeps its board, without menus).
* `rewrite` edits the card the move was picked on; a typed move edits it by id.
* Returns the outcome when the move took the king.
*/
async function playMove(
ctx: Context,
game: ChessGame,
key: string,
from: [number, number],
to: [number, number],
promotion: string,
rewrite: (payload: MessagePayload) => Promise<void>
): Promise<string | null> {
const before: ChessGame = { ...game, board: game.board.map((row) => row.slice()), moves: game.moves.slice() };
const capturedKing = pieceType(game.board[to[0]][to[1]]) === 'king';
const mover = game.turn;
executeMove(game, from, to, promotion);
if (capturedKing) {
const outcome = `👑 <@${playerOf(game, mover)}> took the king and wins!`;
await rewrite(await panel(game, { outcome }));
await mee6.store.delete(key);
return outcome;
}
const historyMode = ctx.settings.board_history || 'single';
if (historyMode === 'every_move') {
await rewrite(await panel(before, { controls: false }));
const sent = await ctx.send(game.boardChannelId, await panel(game));
game.boardMessageId = sent.messageId;
} else {
await rewrite(await panel(game));
}
await save(game, key);
return null;
}
// Settings
mee6.settings({
board_history: {
type: 'string',
label: 'Board display mode',
description: 'How to show the board after moves',
choices: ['single', 'every_move'],
default: 'single',
sample: 'single',
},
});
// /chess play command - challenge someone to a game
mee6.command(
'chess play',
{
description: 'Challenge someone to a chess game',
options: [{ name: 'opponent', type: 'user', description: 'Who to play against', required: true }],
},
async (ctx) => {
const opponentId = ctx.option<string>('opponent');
if (opponentId === ctx.author.id) {
await ctx.reply('You cannot play against yourself!');
return;
}
const opponent = await mee6.getMember(opponentId);
if (!opponent || opponent.bot) {
await ctx.reply('You cannot challenge a bot!');
return;
}
const game: ChessGame = {
white: ctx.author.id,
black: opponentId,
board: initBoard(),
turn: 'white',
boardChannelId: '',
boardMessageId: '',
moves: [],
moveNumber: 1,
};
const sent = await ctx.reply(await panel(game));
game.boardChannelId = sent.channelId;
game.boardMessageId = sent.messageId ?? '';
await mee6.store.set(`chess_${game.boardMessageId}`, game, { ttl: GAME_TTL }); // 24 hour expiry
}
);
/** The game a member is playing, wherever it is */
async function findGame(userId: string): Promise<{ game: ChessGame; key: string } | null> {
const keys = await mee6.store.keys();
for (const key of keys) {
if (key.startsWith('chess_')) {
const g = await mee6.store.get<ChessGame>(key);
if (g && (g.white === userId || g.black === userId)) return { game: g, key };
}
}
return null;
}
// /chess move command - make a move by typing it; the menus on the card do the same
mee6.command(
'chess move',
{
description: 'Make a chess move',
ephemeral: true,
options: [
{ name: 'from', type: 'string', description: 'From square (e.g. e2)', required: true },
{ name: 'to', type: 'string', description: 'To square (e.g. e4)', required: true },
{
name: 'promotion',
type: 'string',
description: 'What a pawn on the last rank becomes (a queen by default)',
choices: [
{ name: 'Queen', value: 'queen' },
{ name: 'Rook', value: 'rook' },
{ name: 'Bishop', value: 'bishop' },
{ name: 'Knight', value: 'knight' },
],
},
],
},
async (ctx) => {
const fromStr = ctx.option<string>('from').toLowerCase();
const toStr = ctx.option<string>('to').toLowerCase();
const found = await findGame(ctx.author.id);
if (!found) {
await ctx.reply('You are not in an active game. Use `/chess play @someone` to start one!');
return;
}
const { game, key } = found;
// Check it's this player's turn
if (ctx.author.id !== playerOf(game, game.turn)) {
await ctx.reply('It is not your turn!');
return;
}
// Parse squares
const from = parseSquare(fromStr);
const to = parseSquare(toStr);
if (!from || !to) {
await ctx.reply('Invalid square notation. Use format like `e2` or `d7`.');
return;
}
// Validate move
if (!isValidMove(game, from, to)) {
await ctx.reply('That is not a valid move for that piece!');
return;
}
const outcome = await playMove(ctx, game, key, from, to, ctx.option<string>('promotion') || 'queen', (payload) =>
mee6.editMessage(game.boardChannelId, game.boardMessageId, payload)
);
await ctx.reply(outcome ? `Played ${game.lastMove}. You took the king — you win! 👑` : `Played ${game.lastMove}.`);
}
);
/** Resign a game: the card shows the final position and who won */
async function resign(
game: ChessGame,
key: string,
userId: string,
rewrite: (payload: MessagePayload) => Promise<void>
) {
const winner = userId === game.white ? game.black : game.white;
await rewrite(await panel(game, { outcome: `🏳️ <@${userId}> resigned — <@${winner}> wins!` }));
await mee6.store.delete(key);
}
// /chess resign command - give up
mee6.command(
'chess resign',
{
description: 'Resign from your current chess game',
},
async (ctx) => {
const found = await findGame(ctx.author.id);
if (!found) {
await ctx.reply('You are not in an active game!');
return;
}
const { game, key } = found;
await resign(game, key, ctx.author.id, (payload) =>
mee6.editMessage(game.boardChannelId, game.boardMessageId, payload)
);
await ctx.reply('You have resigned from the game.');
}
);
// ---------------------------------------------------------------------------
// The card's menus and buttons
// ---------------------------------------------------------------------------
/** The game on the card that was clicked, or null after telling the member why not */
async function cardGame(ctx: Context): Promise<{ game: ChessGame; key: string } | null> {
const key = `chess_${ctx.message?.id ?? ''}`;
const game = await mee6.store.get<ChessGame>(key);
if (!game || game.boardMessageId !== ctx.message?.id) {
await ctx.reply({
content: 'This game is over or has expired — start a new one with `/chess play`.',
ephemeral: true,
});
return null;
}
if (ctx.author.id !== game.white && ctx.author.id !== game.black) {
await ctx.reply({
content: `This game is between <@${game.white}> and <@${game.black}> — challenge someone with \`/chess play\`.`,
ephemeral: true,
});
return null;
}
return { game, key };
}
/** Only the player to move may use the move menus */
async function refuseOutOfTurn(ctx: Context, game: ChessGame): Promise<boolean> {
const toMove = playerOf(game, game.turn);
if (ctx.author.id === toMove) return false;
await ctx.reply({ content: `It is <@${toMove}>'s turn — wait for their move.`, ephemeral: true });
return true;
}
mee6.on('select', async (ctx) => {
const customId = ctx.customId ?? '';
if (!customId.startsWith('chess:')) return;
const found = await cardGame(ctx);
if (!found) return;
const { game, key } = found;
if (await refuseOutOfTurn(ctx, game)) return;
if (customId === 'chess:piece') {
// Step one picked a piece: show where it can go
const from = parseSquare(ctx.values[0] ?? '');
if (!from || pieceColor(game.board[from[0]][from[1]]) !== game.turn || !movesFrom(game, from).length) {
await ctx.reply({ content: 'That piece cannot move now — pick another one.', ephemeral: true });
return;
}
await ctx.editOriginal(await panel(game, { picked: from }));
return;
}
if (customId.startsWith('chess:to:')) {
// Step two picked a square: play the move
const from = parseSquare(customId.split(':')[2] ?? '');
const [square, promotion] = (ctx.values[0] ?? '').split('=');
const to = parseSquare(square ?? '');
if (!from || !to || !isValidMove(game, from, to)) {
await ctx.reply({ content: 'That move is no longer possible — press Back and pick again.', ephemeral: true });
return;
}
await playMove(ctx, game, key, from, to, promotion || 'queen', (payload) => ctx.editOriginal(payload));
}
});
mee6.on('button', async (ctx) => {
const customId = ctx.customId ?? '';
if (customId !== 'chess:back' && customId !== 'chess:resign') return;
const found = await cardGame(ctx);
if (!found) return;
const { game, key } = found;
if (customId === 'chess:resign') {
await resign(game, key, ctx.author.id, (payload) => ctx.editOriginal(payload));
return;
}
// Back to the piece menu
if (await refuseOutOfTurn(ctx, game)) return;
await ctx.editOriginal(await panel(game));
});
The pictures this example ships with. Remix it to change them or add your own.
bishop_bbishop_wking_bking_wknight_bknight_wpawn_bpawn_wqueen_bqueen_wrook_brook_w