ParlorNet
Turn-based game server for any computer, old or new
Clients | Protocols | Browsers | Telnet programs | Docs | Source

Adding a game

A game is four new files and nothing else. None of them is shared with another game, so several games can be built at once without touching the same file:

FileWhat it is
plugins/<game>/plugin.pyThe rules: a game plugin as in plugins.md. The core finds it and lists the game in GAM.
docs/types/<game>-1.mdThe type spec: view lines, move tokens, events, sizes.
adapters/games/<game>.pyThe frontend module: the view parser, the event texts, the web board and images, the telnet screens and the Games page text. The registry finds it.
tests/test_<game>.pyThe plugin's tests and the frontend's tests.

<game> is the type word: reversi, gridwords, cannonfire. The plugin's INFO type, the spec's file name, the module's file name and the start of its KEY all use it.

With the plugin and the module in place, the game appears with no other edit in the web lobby (a Start button), the telnet menu (a "Start a new ... table" row and the game picker; one entry per game, whatever its rulesets), the welcome page's Games list, the Games page (/games.htm) and the game's own page (/games/<type>.htm), and the Frontends and Protocols pages.

Do not edit adapters/web.py, adapters/telnet.py or adapters/common.py for a game. In web.py, GAMES (the planned games in build order) and GAME_ABOUT (the planned games' text) stay as they are: once the module exists, its NAME, PLAYERS and ABOUT are used instead and the row keeps its place. The game's frontends need nothing from the module: every browser and telnet program is listed for every game, and a period client (one that reaches a server extension) goes in PERIOD in adapters/clients.py, with the game's type in its games.

Reversi is the worked example throughout: plugins/reversi/plugin.py, docs/types/reversi-1.md, adapters/games/reversi.py, and its tests in tests/test_adapters.py and tests/test_core.py. Backgammon (adapters/games/backgammon.py) shows a staged game, dice, a picked-up piece and its own glyphs.

1. The plugin

Follow plugins.md: one JSON request per line on stdin, one reply per line on stdout, pure functions of their arguments, all randomness from the seed in the state. INFO gives the type word, version, display name (the same as the module's NAME), rulesets, player counts, flags (staged for multi-step turns, nomoves for no move list, drop for a game of three or more where a player can leave and the others play on) and options. A game flagged drop answers the drop op: Rummy Tile Classic (plugins/rummytile/plugin.py) is the worked example, and Dots and Boxes and Cannon Fire do the same. view returns the type's view lines, not a rendered board. plugins/reversi/plugin.py is complete in under 200 lines.

The core loads every plugins/<game>/plugin.py it finds at start; an operator can switch a game off in the admin menus (games.off).

2. The type spec

docs/types/<game>-1.md, in the form of types/reversi-1.md: players, flags, rulesets and options; static geometry (BRD and the like, flag G); the view lines in a table; the move tokens; the events; the sizes in bytes. Every view starts V <key> <seq>, and the common lines (S, T, M, CLK) mean what protocol.md says; say whose turn it is with W seat, as Reversi and Backgammon do. Specs for planned games may already exist as drafts (Grid Words, Cannon Fire); update them as the game is built.

Move tokens go on a protocol line (MOV 3 d3), so they are ASCII letters, digits and - _ / .: the protocol's name characters ([A-Za-z0-9_-], protocol.md) plus / and . for coordinates and steps (Grid Words writes a blank as _X). A move of several tokens is sent space-separated.

3. The frontend module

adapters/games/<game>.py defines the names below. The registry (adapters/games/__init__.py) imports every module in the package whose name does not start with _, checks that these names are there, and skips (with a line on stderr) a module that lacks one, so one broken game never takes the others down. tests/test_games.py fails on a skipped module.

The module imports what it needs from adapters.telnet (the screen framework), adapters.web (esc, a, make_gif, board_html, hidden_fields) and adapters.board (Canvas, imported as Picture where the module also uses telnet's Canvas). Those modules import the registry, which loads the game modules only when first asked, so the imports do not go round in a circle.

What the game is

NameReversi'sMeaning
KEY"reversi/1"The game type and version, as in GAM.
NAME"Reversi"The display name. For a planned game, exactly the name in web.GAMES ("Grid Words"), so the Games table keeps it in its place.
ORDER1The place in the build order (README.md): Reversi 1, Backgammon 2, Grid Words 3, Cannon Fire 4, Dots and Boxes 5, Five in a Row 6, Mancala 7, Checkers 8, Naval Combat 9, Rummy Tile Classic 10. Menus, the lobby and the tables list games in this order.
PLAYERS"2"Players as text: "2" or "2-4" (the Games table uses the core's numbers when it hosts the game).
ABOUT(about, [rules])For /games.htm. about: two or three sentences in ParlorNet's own words on what the game is. rules: one plain sentence or two per ruleset and option this server supports, from the type spec. Plain ASCII text, generic names only: never a trademark (Othello, Scrabble, Battleship, Rummikub, Kalah, Scorched Earth...); the games page test checks some of these.
RULE_NAMES(none: one ruleset)Optional. {ruleset: display name} for a game with several rulesets (Mancala: {"kalah": "store rules", "oware": "Oware rules"}). When the plugin lists more than one ruleset, the web lobby's form has a rules select and the telnet menu asks with a picker, both showing these names (the ruleset word with a capital when a name is missing), and the first ruleset in the plugin's list is the default. A game whose plugin takes more than two players gets a players select and picker the same way, sent as players=n on NEW.

The view and the events

parse_view(lines) turns the VUE reply (the lines before OK) into a dict. Both frontends read these keys, so every game's dict has them:

KeyMeaning
seqThe view's sequence number, from V key seq.
rowsTruthy once the game has started. Before that both frontends show "Waiting for an opponent". Reversi keeps its board rows here (empty before the first view with a board); Backgammon sets True once there are checkers. A view of only V <key> 1 must give a falsy rows.
turnThe seat to move (W), -1 when none.
movesThe legal move tokens (M lines); empty for a nomoves or CHK game.
statusThe S line. The web page shows it, and treats "Game over" in it as the end.
clock(seat, seconds left, seconds per turn) from CLK, or None.

Add whatever else the game needs (Reversi: n, counts; Backgammon: pts, bar, dice, phase ...).

describe_event(text, names) turns one of the game's own events (the EVT payload after the sequence number) into a line for the log: "ann plays d3 (flips 2)". names are the seated players' names by seat. Return None for any event that is not the game's; return "" to show nothing for an event the log does not need. The shared events (JOIN, LEAVE, START, PASS, CHT, END resign|timeout|win|draw|abandoned, INVITE, UNINVITE) are described by the adapters; describe END yourself only when the game's result has another form (Backgammon's END win seat points kind).

The web page (HTML 3.2)

web_parts(v, tid, link, seat, names, sel) returns four strings of HTML: (board, side, hint, actions). The table page puts the board on the left; the side panel, the status line followed by the hint, the clock, the actions, the log and the page's own links on the right. It is called only once rows is truthy. v is the parsed view, tid the table, seat the viewer's seat (-1 for a watcher), names the seated names (padded with -), sel what the player picked last (see SEL_RE), or "".

link(path, **query) makes a link to a page of this site that keeps the player's session (s=, for a browser without cookies), the action check (x=, which every page that changes something needs) and the display choices; build every link with it, never by hand. A move is a link to /move.htm with t=tid and mv=<move>: link("/move.htm", t=tid, mv="d3"). Backgammon's staged turns also use /und.htm and /end.htm (link("/und.htm", t=tid)). A two-step move (pick a piece, then its target) is a link back to /table.htm with sel= (Backgammon's checkers). A move typed into a form submits to /move.htm with a field named mv, or with the game's own fields (MOVE_FIELDS, below); put the query of link("/move.htm", t=tid) into hidden fields with hidden_fields(link("/move.htm", t=tid)) from web.py, as invite_html does, so the form carries x= and s= too.

NameMeaning
MOVE_REA compiled regex matching every mv= value the page can send (Reversi: ^[a-z][0-9]{1,2}\Z; end with \Z, not $, which also matches before a final newline). /move.htm sends a value on only if some game's MOVE_RE matches it; the core then checks the move. Never match a CR, LF or anything outside the move token characters.
SEL_REA compiled regex for sel= values, or None when the game picks nothing first.
MOVE_FIELDS, move_from_fieldsOptional. A move typed into several form fields: MOVE_FIELDS is the fields' names in order (1 to 6 names of 1 to 8 letters a-z, none of the site's own: s, x, t, mv, sel ... as RESERVED_FIELDS in adapters/games/__init__.py lists), and move_from_fields(values) takes their values in that order and returns the move, or None when they do not make one. A /move.htm (or /check.htm) request without mv= looks up the table's game, checks every field (printable ASCII, at most 32 characters, given at most once; spaces round it are trimmed; a field left out is ""), builds the move and sends it only if the game's MOVE_RE matches it. Cannon Fire: ["angle", "power", "dir", "dist"] makes FIRE 45 60 from its shot form (angle and power) or MOVE L 3 from its move form (dir and dist), and nothing from a mix of the two; Grid Words: ["sq", "dir", "letters"] (a start square, a select of H or V, the letters) makes PLAY 8 8 H HELLO. The plugin still checks the move itself.
WEB_CHECKOptional, True for a game whose page can preview a move with CHK (Grid Words). A form or link to /check.htm (the same t=, mv= or MOVE_FIELDS, the same checks as /move.htm) sends CHK for that table and shows the table page again, with v["check"] = (move, reply) in the parsed view: reply is the core's answer about the move (OK ... or ERR ILLEGAL reason), or None when the core said something else (not seated, no game running). web_parts shows it; with None it may fall back on what the page can work out itself. That page also gets the move as sel when SEL_RE takes it, so the forms keep it, and it does not refresh itself. A game without WEB_CHECK gets an error page from /check.htm.
images(){path: GIF bytes}: the game's tiles (squares, pieces, dice), which board_image draws with. They are also served at those paths, made once on the first request, with a day's Cache-Control. New games put them under /img/<game>/ (Reversi's are at /img/*.gif and Backgammon's at /img/bg/, where they were before the registry). web.make_gif(w, h, palette, pixels) writes a GIF of up to 8 colours. A game that draws everything itself returns {} (Cannon Fire), as does one with no images (Rummy Tile).
board_image(v, seat, sel)Optional, and expected of every game with a board: the whole board as one image, an adapters.board.Canvas (below).
board_click(v, seat, sel, x, y)Optional: for a board that is clickable anywhere (canvas.anywhere = True), the link a click at the pixel x, y stands for, as (path, {query}), or None. Cannon Fire drives the tank to a point on the ground within a move's reach, ("/move.htm", {"mv": "MOVE R 3"}), and aims the barrel at any other point: ("/table.htm", {"sel": "60-50"}).
web_events(v, events)Optional: adds to the parsed view what the board shows from the table's events (every EVT payload so far, in order). Cannon Fire keeps the last shot's path (TRJ), burst (HIT) and dug columns (ZCH) in v["trail"], v["burst"], v["dug"]. The web calls it for the page and for the board image alike.

One image per board

A board is one GIF, not a table of small ones: each image costs a browser a request and, with HTTP/1.0, a new connection, and a firewall that limits new connections per address (parlornet.org allows 30 a minute on its ports) cuts off a page of dozens of images. board_image(v, seat, sel) draws the board on a Canvas and returns it; web_parts shows it with

board = board_html(board_image, v, tid, link, seat, sel, "Reversi board")

adapters/board.py has what a board needs, in pure Python:

board_html renders the canvas into a GIF (LZW, encode_gif), keeps it in a small cache (the last few boards of each table, about 1.5 MB in all) and writes:

<a href="/click.htm?t=..&q=..&st=..&d=..&x=.."><img src="/board.gif?t=..&q=..&st=..&d=.." width=W height=H border="0"
 alt="..." ismap usemap="#board"></a>
<map name="board"><area shape="rect" coords="112,80,143,111" href="/move.htm?...&mv=d3" alt="d3"> ...</map>

Keep a board image small: a palette GIF of a few KB, under about 640 pixels wide, drawn in a few milliseconds. Draw clear outlines, so pieces stay apart from the board when a browser dithers to black and white, and never let colour be the only mark (a letter, a shape, a count). The page itself then has one image; small decorations of their own count against the limit of four images a page that web_page checks.

HTML 3.2 rules, as for every page here (the test helpers check them):

Telnet: the screens

Two classes, from the framework in adapters/telnet.py:

Reversi puts what both share in a base class (ReversiBase(telnet.GameBase): parse, describe, move_word), then class AnsiReversi(ReversiBase, AnsiGame) and class PlainReversi(ReversiBase, PlainGame), and ends with AnsiScreen, PlainScreen = AnsiReversi, PlainReversi.

GameBase keeps the table: self.v (the parsed view), self.names, self.me (the player's seat, -1 when watching), self.log, self.over (the end text, once the game ends), self.tid. It does the core requests (refresh, pull, move(token), staged("UND" or "END", what), chat, resign) and answers playing(), my_turn() and clock(). Override in the shared base:

HookReversi's
parsestaticmethod(parse_view)
describe(text)its describe_event, then telnet.describe_event for the shared events
move_word(cmd, words)a typed command to the move it stands for, or None: cmd if SQUARE_RE.match(cmd) else None. cmd is the first word in lower case, words the whole line's words as typed; return several tokens space-separated for a multi-token move.
play_word(word)(the default: self.move(word).) Backgammon's sends undo and end as UND and END and answers a resignation offer.
playing(), my_turn()(the defaults.) Override when "my turn" needs more than turn and moves, as Backgammon's phases do.
on_event(text)Called for every new event; Backgammon keeps the last roll.

The typed commands menu (and m, leave, back, quit, q, exit), redraw (r, refresh), help (?), say (chat) and resign come first, so a move word cannot be one of them.

AnsiScreen draws the whole screen in compose(), which returns a telnet.Canvas; the framework sends only the cells that changed. The hooks:

HookReversi's
compose()title_bar, the board, the panel (box, rule, players, whose turn, the clock, then draw_log), the hint or message on row 21, input_line on row 22, status_bar on row 23. While the game has not started, draw_waiting(cv, x, y) puts the "Waiting for an opponent" box over the board.
cursor_at()Where the terminal's cursor sits (on the cursor square), or None.
snap()After a new view: put the cursor somewhere useful (on a legal square when it becomes the player's move). Remember self.was_my_turn.
on_arrow(k)UP, DOWN, LEFT, RIGHT move the cursor.
on_enter()Enter or Space with nothing typed: place a disc on the cursor square.
on_click(value)A mouse click on a hot area: cv.hot_area(x, y, w, h, ("sq", col, row)) while drawing makes the cells clickable, and the click comes back as that tuple. Status bar items are clickable already (as their keys).
on_escape()Esc with nothing typed. The default leaves for the menu; Backgammon first puts a picked-up checker back.
HOTKEYS, hotkey(k)Letters taken as commands when the input line is empty. The default handles r (resign, asks first), t (talk) and ? (help); a game adds its own letters to HOTKEYS and handles them, calling super().hotkey(k) for the rest. A letter followed at once by more typing counts as typing. With letter movement keys (IJKL, ESDF, WASD or HJKL, the session's choice) the four letters always move the cursor, so a hotkey with one of those letters is pressed as : then the letter; the status bar shows such a key as :d by itself, and hints name keys with self.kn("D") (D, or :d).
typing()True while every letter types even on an empty line, so movement letters do not move. The default is False; Grid Words returns True once a word's start is set.
typed_move(word)A typed move: the default plays it, shows an error in red and snaps.
TITLE, HELPThe help box's title and lines (at most 13 lines of at most 50 columns).
LOG_TOP, LOG_ROWSWhere draw_log writes the log.

PlainScreen hooks: lines() (the screen as a list of lines; the board, a side column, the clock and the last four log lines), prompt() (Reversi's: Your move (like d3) > ), HELP_TEXT (what help prints) and BOARD_KINDS (the events that reprint the board; others are printed as a line).

Telnet: fitting 80x24 in every glyph mode

The screen is 80 columns by 24 rows and must fit in every mode:

Checked when the module loads

adapters/games/__init__.py lists the required names in REQUIRED; games.problems(module) says what a module lacks. tests/test_games.py checks, for every module: nothing missing, the plugin and the type spec exist, ABOUT and NAME are ASCII, image paths do not clash and sit under /img/<game>/, and every screen of the game, in every mode, fits 80x24 and says "Waiting for an opponent" before the game starts.

4. Tests

tests/test_<game>.py, in the form of tests/test_backgammon.py for the plugin, plus the frontends. tests/game_checks.py has the frontend checks; a game's tests give them views:

from game_checks import ansi_screens, plain_screen, web_page

from adapters.games import gridwords as G

class Screens(unittest.TestCase):
    def test_full_screen(self):
        for me in (0, 1, -1):                  # each seat, and a watcher
            for mode, (shown, reqs) in ansi_screens(self, G, MIDGAME, me, keys=["RIGHT", "ENTER"]).items():
                ...                            # what should be on the screen, and the MOV requests sent

Cover at least: the waiting view, the opening, a move for each seat and a watcher, a crowded or extreme position (the longest texts, the tallest stacks), the end of the game; the keys, a click and a typed move each sending the right MOV; every MOVE_RE token the web page links to; with MOVE_FIELDS, move_from_fields on good and bad values and a move sent through /move.htm from the fields by a browser signed in with a session (tests/test_cannonfire.py and tests/test_navalcombat.py use Stack and Browser from tests/test_adapters.py; tests/test_gridwords.py runs the core and the web adapter in its own process); web_page checks that every link and form carries s= and x=; with WEB_CHECK, web_parts given a v["check"] of each kind (web_page(..., check=(move, reply)) in tests/game_checks.py). For the plugin: the rules, the events, a whole game over the protocol (test_core.Client). plugins.md also asks for a directory of recorded games per plugin; Reversi and Backgammon do not have one yet.

Run everything before committing:

python3 -W ignore -m unittest discover -s tests -p "test_*.py"

Reversi, file by file

This doc on GitHub


 These pages cover every ParlorNet server. | Source code | ParlorNet is free software.