‹ Roma Tiles

API for bots

A program plays Roma Tiles over one WebSocket with JSON messages. The server keeps the game, applies the rules and scores it. After every change it sends the whole position together with every legal move, so a bot needs no rules of its own: it reads the view and answers. This page is the whole protocol, and is written to be read by a coding agent as well as a person.

Quick start

Socketwss://tiles.roma.ai/api/ws
Keythe header Authorization: Bearer KEY on the WebSocket's opening request. Keys are issued by the site's owner, one per developer. A key is a secret: keep it out of code you publish.
MessagesJSON text frames, both ways, each an object with a "type"
Reference clientrandom_bot.mjs: plays random legal moves, 50 lines, Node 22 or later, nothing to install. Its source is at the end of this page.

Two bots against each other, each with its own key or both with the same one:

node random_bot.mjs wss://tiles.roma.ai/api/ws KEY --name=First --games=3     # prints: room ABCD
node random_bot.mjs wss://tiles.roma.ai/api/ws KEY --name=Second --games=3 --room=ABCD

Anyone can watch the game in a browser at https://tiles.roma.ai/?room=ABCD, and every game under way is listed on the games page.

The loop

  1. Open the socket with your key. Send create (a new room) or join (a room's code).
  2. The server answers joined with your seat's id, then sends a room message, the view, now and after every change in the room.
  3. Find your seat: the index in view.players of the entry whose id is yours. Seats are shuffled when a game starts, so look it up in every view.
  4. When view.play.turn is your seat, send the move for view.save.phase: place, then claim, and sometimes farmer.
  5. Every message you send is answered with ok (carrying a version) or error. After sending, wait for that answer, and then act only on a view whose version is at least the answer's. The view that shows your move may arrive just before or just after its ok.
  6. When view.result is not null the game is over. The room's host sends start for the next one.

A turn

The game is a tile-laying game for 1 to 6 players with 178 tiles: cities, roads, monasteries, gardens and fields, a river at the start, inns and cathedrals, trade goods, and for each player 7 meeples, a large meeple, an abbot, a builder and a pig. A game starts with the river's spring on the board at 0,0 and seat 0 deciding whether to claim on it. Then players take turns:

PhaseWhat you sendWhat it does
place{"type":"place","x":2,"y":0,"rotation":1} Puts the tile in hand (save.hand.tile) on a cell. play.spots[r] lists the cells [x, y] where it fits when turned r quarter turns clockwise, r from 0 to 3. x grows to the east, y to the south.
claimone entry of play.claims with "type":"claim" added, or {"type":"claim","feature":null} Puts a meeple on a feature of the tile just placed, or none. Always send it, even when play.claims is empty: it ends the turn. Before it you may send {"type":"unplace"} to take the tile back and place it elsewhere.
pig{"type":"farmer","back":false} Only after a city with a coat of arms was completed and a pig scored: the pig's owner (play.turn, who may be another player than the one who placed) says whether the farmer beside it comes back too.
overnothingThe stock is empty. view.result has the final scores.

A claim is {"feature": 1, "kind": "city", "piece": "meeple"}: the feature's index on the tile, its kind, and the piece (meeple, large or abbot). With "with": "builder" or "with": "pig" the builder or the pig goes with it. {"recall": true} takes the abbot back from the board and scores it. Send back exactly what play.claims offers. A tile of yours that continues the road or city your builder is on gives you another turn after it: play.turn is simply you again.

One full turn, as it goes over the socket (views shortened):

← {"type":"room","version":41,
   "players":[{"id":90211,"name":"First",...},{"id":731554,"name":"Second",...}],
   "save":{"phase":"place","hand":{"tile":"V3-D","rotation":0,"player":1},"scores":[12,9],
           "stock":["V3-A","V3-B",...],"moves":[...]},
   "play":{"turn":1,"spots":[[[0,1],[2,0]],[[0,1]],[],[[1,-1]]],"claims":[],...}}
→ {"type":"place","x":2,"y":0,"rotation":0}
← {"type":"ok","version":42}
← {"type":"room","version":42,"save":{"phase":"claim",...},
   "play":{"turn":1,"claims":[{"feature":0,"kind":"road","piece":"meeple"},
                              {"feature":1,"kind":"city","piece":"meeple"},
                              {"feature":1,"kind":"city","piece":"large"}],...}}
→ {"type":"claim","feature":1,"kind":"city","piece":"meeple"}
← {"type":"ok","version":43}
← {"type":"room","version":43,"save":{"phase":"place","hand":{"tile":"V3-K","player":0},...},
   "play":{"turn":0,...}}

A move the rules refuse changes nothing and is answered with an error; the turn stays open:

→ {"type":"place","x":5,"y":5,"rotation":0}
← {"type":"error","code":"illegal","message":"tile V3-D doesn't fit at 5,5 turned 0"}

Messages you send

MessageMeaning
{"type":"create","name":"MyBot"}A new room; you take its first seat and are its host. The answer's room is its four-letter code.
{"type":"join","room":"ABCD","name":"MyBot"}A seat in that room, before its game starts. A started or full room is watched instead (seat is null). With "token" (from your earlier joined) you take your seat back after a dropped connection, mid-game too.
{"type":"lobby"}Before joining: answered once with {"type":"rooms","rooms":[{"code","host","players"}]}, the open rooms made over the API.
{"type":"start"}The host starts the game with everyone seated (one seat is enough), or the next game once one is over.
{"type":"settings","shuffle":false}The host: seats play in the order they came in, instead of a random order each game.
{"type":"add_player","name":"Second"}One more seat played from this same connection, before the game: one program may play several seats.
{"type":"remove","seat":1}The host takes an absent player's seat away, before a game.
{"type":"name","name":"NewName"}Renames your seat. Names are at most 16 characters.
place, unplace, claim, farmerThe moves, above.

One connection is in one room. To play several games at once, open one connection for each.

Messages you get

MessageMeaning
{"type":"joined","room","seat","id","token","creator"}You are in the room. id identifies your seat in every view; token takes the seat back on a new connection.
{"type":"ok","version"}Your message was done; views from this version on show it.
{"type":"error","code","message"}Your message was refused and nothing changed. See errors.
{"type":"room", ...}The view: the whole state of the room, sent to everyone in it after every change.
{"type":"activity", ...}What a person to move is doing with their tile in the page. Ignore it.

The view

FieldMeaning
room, versionThe room's code; a number that grows with every change.
players[]The seats in turn order: id, name, online, api (a program's seat), bot (not null: the server plays it), color, screen (the id of the seat whose connection plays it).
hostThe seat that may send start: the room's maker while connected, else the first player still there.
started, gameWhether a game has begun; the game's id, for its replay.
save.phaseplace, claim, pig or over.
save.handWhile placing: {"tile": id, "player": seat, "rotation", "setAside"}. Null otherwise.
save.moves[]The board: every tile placed, in order, the spring first. Each has tile, x, y, rotation, player, meeple (a claim, or null), and the standing after it: scores, potentials, meeplesLeft.
save.stock[]The ids of the tiles still to be drawn, sorted by id: what is left, not the order it comes in.
save.scores, save.potentials, save.meeplesLeftPer seat: points scored so far; what unfinished claims and fields would add if the game ended now; standard meeples in hand.
play.turnThe seat whose decision it is. Null when the game is over.
play.spotsFour lists, one per rotation, of the cells [x, y] where the tile in hand fits.
play.claimsThe legal claims on the tile just placed (empty outside the claim phase).
play.pig, play.pigAtIn the pig phase: whose say it is, and the tile (index in save.moves) their farmer is on.
play.groups[]The features that matter now (every claimed one, then those of the last tile), each joined across tiles: kind, tiles (indices in save.moves), open (open edges), points (worth now), done, owners (the seats that score it), meeples, shields, inn, cathedral, goods. play.claimed and play.last index into it.
play.players[]Per seat: whether large, abbot, builder, pig are in hand; goods tokens (grain, cloth, chicken); points by source (city, road, monastery, garden, field, goods).
resultNull until the game is over, then {"scores": [..], "winners": [seats], "timeout": seat or null}. scores are the final scores (points plus what the end counts).
times, waitedEach seat's thinking time this game, and the seconds since the last move.

A view of a game near its end is about 100 kB. Fields not listed here are for the page; new fields may be added, so ignore what you do not know.

Time and limits

LimitValue
Time for a turn30 seconds for the tile and its meeple together (taking the tile back gives no more), and 30 seconds for a say in the pig phase. A person playing in the room has 5 minutes. When it runs out the game ends there: result.timeout is that seat, and it is not among the winners.
Messages5 a second after a burst of 20; more are not refused, they wait their turn. So a two-player game takes about 35 seconds at the least. Each message at most 4 kB.
Per key8 connections, 4 rooms at once, 250 games started a day (a key may be given other numbers).
Per address250 games started a day from one IP address, by the API and the website together, finished or not.
Keep-aliveThe server pings every 30 seconds and drops a connection silent for 90 (WebSocket libraries answer pings by themselves), or one that reads nothing for 20.
RoomsA room nobody is connected to makes way when its key needs a room, and is dropped after a while in any case. If a connection breaks mid-game, rejoin with your token: the turn's clock keeps running.

Errors

WhereWhatMeaning
opening the socketHTTP 401No key, or not one of the server's.
opening the socketHTTP 429The key has all its connections open.
error.codenot_your_turnThe decision is another seat's. Wait for a view with play.turn yours.
error.codeillegalA move the room did not take: against the rules, or not yours to make. message says why.
error.codelimitOne of the key's limits. message says which, and when the next try can succeed.
error.codeno_roomNo room with that code.
error.coderefusedAnything else (only the host starts a game, the room is full, ...). message says what.

The tiles

GET https://tiles.roma.ai/api/tiles with your key in the same header returns every tile as the rules read it, so that a claim's feature index and a tile's edges mean something to a bot that evaluates positions:

{"start": "V3-F1", "goods": ["grain", "cloth", "chicken"],
 "tiles": [{"id": "V3-D", "features": [
     {"kind": "city", "edges": ["N"], "shield": false, "inn": false, "cathedral": false, "goods": [0,0,0], "cities": []},
     {"kind": "road", "edges": ["E", "W"], ...},
     {"kind": "field", "edges": ["En", "Wn"], "cities": [0], ...},
     {"kind": "field", "edges": ["Es", "Se", "Sw", "Ws"], "cities": [], ...}]}, ...]}

The box has one of each tile, so an id names one tile. Features are listed in the order claims number them. edges are on the unturned tile: a city, road or river touches whole sides N E S W; a field touches half sides, named clockwise from the top left Nw Ne En Es Se Sw Ws Wn (Nw is the west half of the north side, En the north half of the east side). A tile placed with rotation r is turned r quarter turns clockwise: its N edge then faces east for r = 1. Two features on one tile are never connected. A field's cities are the indices of the cities it borders on the tile: above, the field north of the road borders the city, the field south of it does not.

Games, results and replays

What the games page and a replay show, as JSON. No key is needed; people's games are listed too.

GET https://tiles.roma.ai/api/games lists the games under way (live, the latest move first) and the finished ones (finished, the latest end first, 20 a page). ?page=N turns the finished ones' pages (the first is 1), ?api=1 keeps the games of API rooms only.

{"live": [{"game": "k3v9x0aq2m", "room": "QMBD", "api": true,
           "players": [{"name": "MyBot", "color": 0, "bot": null, "api": true, "online": true, "score": 12},
                       {"name": "Other", "color": 1, "bot": null, "api": true, "online": true, "score": 9}],
           "turn": 1, "tiles": 31, "left": 147, "started": 1794450848982, "waited": 2, "watching": 0}],
 "finished": [{"game": "jjbuuvx5b1", "api": true,
               "players": [{"name": "MyBot", "color": 0, "bot": null, "api": true, "score": 118},
                           {"name": "Other", "color": 1, "bot": null, "api": true, "score": 97}],
               "winners": [0], "timeout": null, "tiles": 178,
               "started": 1794450848982, "ended": 1794450917735}],
 "total": 243, "page": 1, "pages": 13}
game, roomThe game's id, for its replay; the room's code, to watch it.
playersIn seat order. api: the seat is a program's; bot: the kind of the site's bot, or null. score: the points so far; in a finished game, the final ones.
winners, timeoutThe seats that won (more than one in a tie); the seat that ran out of time, or null. A seat that ran out of time never wins.
turn, tiles, leftThe seat to move; the tiles on the board; the tiles not yet placed.
started, endedMilliseconds since 1970. waited: seconds since the last move; watching: people watching now.

GET https://tiles.roma.ai/api/games/ID is one game, under way or finished, by view.game: {"save", "positions", "times", "clocks", "result"}. save is the last view's save with every move in save.moves; positions[k] is play after move k (its groups have every road, city, field and monastery with its owners and points); times is each seat's thinking time in ms; result is as in the last view, null while the game is under way. 404 for an id that is no game.

Fair play

The reference client

random_bot.mjs, complete. Replace act's random choices with your bot's.

// A reference client for Roma Tiles's API (the page at /api explains it): plays random
// legal moves. Node 22 or later, nothing to install.
//
//   node random_bot.mjs wss://tiles.roma.ai/api/ws KEY                     makes a room, prints its code
//   node random_bot.mjs wss://tiles.roma.ai/api/ws KEY --room=ABCD         joins that room
//   options: --name=Random  --players=2 (the maker starts once so many are seated)  --games=1
const [url, key, ...rest] = process.argv.slice(2);
const opt = Object.fromEntries(rest.map(a => a.replace(/^--/, '').split('=')));
const name = opt.name ?? 'Random', players = Number(opt.players ?? 2), games = Number(opt.games ?? 1);
const pick = list => list[Math.floor(Math.random() * list.length)];

const ws = new WebSocket(url, {headers: {Authorization: `Bearer ${key}`}});
let me, view, need = 0, waiting = false, played = 0, counted = '';
const send = message => {
    ws.send(JSON.stringify(message));
    waiting = true; // until the server answers it: ok or error
};
ws.onopen = () => send(opt.room ? {type: 'join', room: opt.room, name} : {type: 'create', name});
ws.onerror = e => console.error(e.message || 'no connection: is the address right, and the key (a wrong one is refused, 401)?');
ws.onclose = () => process.exit(played >= games ? 0 : 1);
ws.onmessage = event => {
    const m = JSON.parse(event.data);
    if (m.type === 'joined') console.log(`room ${m.room}`, me = m.id);
    if (m.type === 'room') view = m; // the whole state, after every change
    if (m.type === 'ok') [waiting, need] = [false, m.version];
    if (m.type === 'error') return console.error(m.code, m.message), ws.close();
    // Act only on a view that shows our last message done
    if (view && !waiting && view.version >= need) act();
};

function act() {
    const seat = view.players.findIndex(p => p.id === me); // seats are shuffled at each start
    if (!view.started || view.result) {
        if (view.result && counted !== view.game) {
            counted = view.game;
            played++;
            const {scores, winners, timeout} = view.result;
            console.log(`game ${view.game}: ${scores.join(' : ')}, ${winners.includes(seat) ? 'won' : 'lost'}${timeout === null ? '' : `, seat ${timeout} ran out of time`}`);
            if (played >= games) return ws.close();
        }
        if (view.host === seat && view.players.length >= players) send({type: 'start'});
        return;
    }
    const {turn, spots, claims} = view.play;
    if (turn !== seat) return;
    if (view.save.phase === 'place') {
        send(pick(spots.flatMap((cells, rotation) => cells.map(([x, y]) => ({type: 'place', x, y, rotation})))));
    } else if (view.save.phase === 'claim') { // always answered: it ends the turn
        send({type: 'claim', ...(claims.length && Math.random() < 0.5 ? pick(claims) : {feature: null})});
    } else if (view.save.phase === 'pig') {
        send({type: 'farmer', back: Math.random() < 0.5});
    }
}

Any WebSocket client that can set a header on the opening request works the same way, in any language. A page in a browser cannot set that header, so a bot is a program of its own, not a web page.