Metadata-Version: 2.5
Name: algogames
Version: 0.1.0
Summary: The AlgoGames SDK, and the app that plays algos on your own machine
Project-URL: Homepage, https://algogames.ai
Project-URL: Documentation, https://algogames.ai/docs
Author-email: Hudson Hochstedler <hudson.hochstedler@algogames.ai>, Harrison Hochstedler <harrison.hochstedler@algogames.ai>
License-File: LICENSE
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.11
Requires-Dist: fastapi>=0.115
Requires-Dist: numpy>=2
Requires-Dist: uvicorn>=0.30
Description-Content-Type: text/markdown

# AlgoGames

The Python SDK for [AlgoGames](https://algogames.ai), and the app that plays
algos on your own machine. One install gives you both:

```bash
pip install algogames
```

`algogames` is what an algo imports: an interface per game, used as the class it
is. `algogames.app` plays algos against the real engines and shows you the
match.

## The app

Play an algo against the real engines and watch the match, on your own machine
and offline. Nothing is uploaded, and nothing needs Docker: the engines are
native executables, each algo runs as an ordinary Python process, and the match
is drawn by the website's own replay viewer.

```
┌──────────────────────────────────────────────────────────────┐
│ AlgoGames/local  Game Racing ▾  Algos 4  History 3    [Run ▾] │
├──────────────────────────────────────────────────────────────┤
│                                          │ test_algo    ▸    │
│        the website's replay viewer       │ ─────────────     │
│              (the same module)           │ Finish  2         │
│                                          │ Distance  871.4   │
│  ◀◀  ▶  ▶▶  x1  ────●──────────  412/900 │ console output... │
└──────────────────────────────────────────────────────────────┘
```

## Use it

```bash
python -m algogames.app
```

`algogames-app` is the same thing as a command. Nothing else needs installing or
building: the package carries the engines for your platform, the viewer and a
starter algo for every game.

It opens the app in a window of its own. Everything is chosen there: the game,
an algo for each seat, and the seed. A seat takes the path to any algo: type it,
pick one the app found in the folder you started it in, choose a `.py` file or
an algo's folder with **File…** or **Folder…**, or drop one on the seat.

`--port` serves it somewhere other than 7777. `--no-window` serves it with no
window, for a browser, and prints the address. Run it while the app is already
open and the open window comes to the front instead.

On a Linux whose C library is musl, such as Alpine, the app has no window, since
the toolkit it draws one with on Linux (Qt) can't be installed there with pip.
Serve it with `--no-window` and open the address it prints; scripts play
matches there as anywhere.

While a match plays, **Run** turns into **Stop**, which ends the match early.
The run is kept as *stopped*, and you can still replay what it played.

To stop the app, close its window. That also stops a match that is still
playing. With `--no-window`, press `Ctrl`+`C` in its terminal.

### Which Python your algo runs on

The one running the app. An algo imports the same `algogames` the app runs
from, and anything else it imports has to be installed beside it:

```bash
pip install algogames torch
```

### Watching a match as it plays

Press Run and the viewer follows the match immediately rather than waiting for
the replay. The engine streams each tick as it becomes final (`--stream-port`),
the server passes each on as it is, in the `frame` events the viewer reads, and
the board advances at the game's own rate. Scrub back at any point to look at
something; drag to the end to start following again.

Joining late or reloading mid-match is fine: the server keeps the frames, so a
viewer opening at tick 3000 gets the first 3000 and then follows, and a dropped
connection resumes from the tick it left off at.

Chess is the one game where live adds little - it is not wall-clock paced, so
the whole game arrives in a couple of seconds.

Each run's replay is kept in a temp folder of the app's session
(`algogames-runs-*` under your system's temp directory), which the system
clears in time. To keep replays, play from Python with `replay_dir=`.

### Your algo

- **A single file** defining `on_update(state)`, or `on_my_turn(state)` for chess.
- **A `.zip`** whose `__init__.py` defines one of those. A folder the zip was
  wrapped in is ignored.
- **A package directory** with an `__init__.py`, which is what an algo with
  several modules looks like while you are writing it.

Before a match starts, the app checks for the mistakes that otherwise show up as
a confusing match failure: a syntax error, and nothing for the game to call.
What your algo prints shows on its console as its own line, as what it logs with
your game's interface (e.g. `SnakeInterface.log()`) does.

## From Python

A script can play matches too: a training loop, a sweep of one algo against
several rivals, anything the page's one **Run** doesn't cover. These are the
same matches - the same engines, a process per algo - and nothing starts a
server.

```python
from algogames.app import play

result = play('duel-snakes', ['bots/greedy.py', 'bots/random.py'])

result.ok         # it finished
result.winner     # the seat that won, or None for a draw
result.stats      # the engine's match stats
result.seats      # each seat's stats, in seat order
result.seed       # the seed it played, so the match can be played again
result.frames()   # every tick: its state, and what the algos logged during it
```

A frame's state is what the replay keeps of the game, which is less than an algo
is sent: a Chess frame's is the board as FEN and each side's time left, in
nanoseconds.

`play` waits for the match and takes a `seed=` to repeat one. An algo that
cannot be loaded raises `LocalError`, and an engine that produced no replay
raises `MatchError`: a broken algo should stop a training run rather than
quietly score zero.

For many matches, `play_many` plays several at once and yields each result as it
finishes:

```python
from algogames.app import play_many, Matchup

league = [('duel-snakes', [mine, rival]) for rival in rivals]

for result in play_many(league, workers=4):
    score(result.winner, result.seats)
```

A match that fails there comes back as a result whose `status` is `failed`
instead of raising, so one broken algo doesn't lose a long sweep. Frames are
dropped unless you ask for them with `keep_frames=True`, because one race's
frames are about 12MB. `Matchup(game, algos, seed=...)` gives a matchup a seed
of its own.

To keep the replays as files, name a folder for them. `play` and `play_many`
both take `replay_dir=`, and each finished match's replay is written there as
`<game>-<id>.agr`, gzipped, whether or not its frames are kept. With no folder, no file
is written.

```python
for result in play_many(league, workers=4, replay_dir='replays'):
    print(result.replay_path)   # replays/duel-snakes-3f2a9c01b2d4.agr
```

`games()` lists what can be played and how many seats each game takes.

### Reading a replay

A replay is binary, and `load_replay` reads one: a file `replay_dir` kept
(an `.agr`, gzipped), one downloaded from the site, or an
engine's own `.agr`. It gives each tick of the match as its game's replay state,
which is the whole board as the viewer draws it, not what one algo was sent:

```python
from algogames import load_replay

replay = load_replay('replays/duel-snakes-3f2a9c01b2d4.agr')

replay.game         # 'duel-snakes'
replay.seed         # the seed it played
replay.seats        # how many algos played
replay.finished     # False for a match stopped part-way, which has no stats
replay.stats        # the engine's match stats
replay.seat_stats   # each seat's stats, in seat order
replay.states       # one state per tick, in order; iterating the replay gives these too
replay.logs         # every console line: LogLine(tick, seat, kind, message)

for state in replay:
    print(state.tick, state.snakes[0])

mine = [line.message for line in replay.logs if line.seat == 0 and line.kind == 'algo']
```

`kind` is `'algo'` for what an algo logged, `'error'` for what it wrote to
stderr, and `'engine'` for what the engine told it. Each game's state:

| Game | State | What it holds |
| --- | --- | --- |
| Snake | `SnakeReplayState` | `tick`, `snake` (every cell, head first), `length`, `hunger`, `dead`, `apple` (or `None`) |
| Duel Snakes | `DuelSnakesReplayState` | `tick`, `snakes` (one per seat, head first), `lengths`, `hungers`, `dead`, `apples` |
| Chess | `ChessReplayState` | `tick`, `fen`, `board` (a `ChessBoard`, its pieces with no valid moves listed), `turn`, `turn_num`, `clocks` (white's and black's time left, in ms) |
| Racing | `RacingReplayState` | `tick`, `leader` (a seat), `cars` (a `ReplayCar` per car: `seat`, `pos`, `heading`, `speed`, `lap_progress`, `rank`, `finished`, contacts and more), `track` (a `ReplayTrack`: its name, length, centerline and start, the walls, and the lap time limit) |

A replay keeps only a snake's head each tick, so its body is rebuilt from the
heads before it, as the viewer does.

A script's result reads the same way, without a file: `result.replay()` is what
`load_replay` would give for its match. It has no states for a match that
failed, or one `play_many` played without `keep_frames=True`.

### Watching a scripted match

A match played by `play` has nothing to look at. To watch one, play it in the
app instead: it appears in the app's viewer exactly as if you had pressed
**Run**.

```python
from algogames.app import start

app = start()                      # the app's window, opening one if none is open
summary = app.run('racing', [mine] * 4)
print(summary['status'], summary['stats'])

for event in app.events():         # run.started, run.progress, run.finished...
    print(event['type'])
```

`start()` uses the app already open on port 7777 if there is one, and opens a
window otherwise. `start(new=True)` always opens another, and
`start(window=False)` serves an app with no window that ends with your script.
The window stays open when your script ends, so you can look through what it
played. `app.close()` closes it, as leaving `with start() as app:` does, even if
the window was open before your script found it. `LocalApp(url)` drives an app
at an address without ever closing it.

`run(..., wait=False)` returns as soon as the match starts. `config()`,
`games()`, `algos()`, `runs()`, `run_info()`, `replay()` and `stop()` are the
rest of what the page itself uses.

## From a checkout

Working on AlgoGames itself, the app runs from the repo instead, finding the
engines, the viewer and the starter algos where the repo keeps them. From the
repo root, once:

```bash
npm install && npm run build:viewer    # the replay viewer
uv sync --all-packages                 # the Python environment
```

Then build the engines for your machine, and the game logic the SDK shares with
them, on the repo's `.venv`, which `uv sync` gives the zig compiler:

```bash
# <rid> is win-x64, win-arm64, osx-arm64, osx-x64, linux-x64, linux-arm64, linux-musl-x64 or linux-musl-arm64;
# leave it out for this machine
.venv/bin/python game-engines/build.py --rid <rid>
```

or build them in Docker instead:

```bash
ENGINE_RID=<rid> docker compose --profile tools run --rm engines
```

zig signs a macOS engine ad hoc as it builds it. If macOS still refuses to run
one, sign it yourself:
`codesign --force --sign - game-engines/publish/osx-arm64/{Snake,DuelSnakes,Chess,Racing,libshared_game_logic.dylib}`.

```bash
.venv/bin/algogames-app
```

Anything missing is reported in the app rather than crashing it, naming the
command that fixes it.

### Testing a game

Every game has a test algo under `test-files/test-algos/`, so the app is how you
exercise an engine, with nothing uploaded. Choose the game on the page and put
its test algo, which the page suggests, in each seat. A seed from History plays a
match again exactly.

The app always runs the engines built into `game-engines/publish/<rid>/`.
After changing an engine, build it again; each **Run** starts the engine
afresh, so the next one uses the new build with no restart:

```bash
.venv/bin/python game-engines/build.py
```

### Installing it somewhere else

Installing the package from the repo gives another environment the whole app, as
`pip install algogames` does:

```bash
pip install path/to/AlgoGames/sdks/python/algogames
python -m algogames.app
```

That builds a wheel, and a wheel carries a bundle: this machine's engines, the
viewer, the site's styles, the driver and the starter algos, laid out as the
repo keeps them, so the app finds them the same way in both. It needs the viewer
and the engines built, and says which command to run if either is missing.
Install it again after building either one afresh.

To keep the wheel, or build one for another platform:

```bash
uv build --wheel --out-dir bundles sdks/python/algogames                          # this machine's
ALGOGAMES_RID=linux-x64 uv build --wheel --out-dir bundles sdks/python/algogames  # another platform's
```

Any machine builds any platform's wheel, once that platform's engines are built.

## How it relates to the website

| What | Where it comes from |
| --- | --- |
| The replay viewer, playback, renderers, consoles | `web/src/viewer/` and `web/src/games/`, bundled to `web/dist-viewer/` |
| Palette, type, buttons, dialogs | `web/src/styles/`, served as the site serves it |
| Engines | `game-engines/`, published to `game-engines/publish/<rid>/` |
| The rules `make_pseudo_move` asks, and the counter `time_left` reads, in the algo's own process | the engines' shared game logic, published beside them |
| The SDK and the driver an algo starts from | `sdks/python/algogames/`, `drivers/local_driver.py` |

Only the toolbar, the run list and the two dialogs are this app's own. Change a
renderer and this picks it up on the next `npm run build:viewer`. It has no
accounts, leaderboards or database, and imports nothing from the site's backend.

## Security

There is no sandbox. An algo runs with your permissions, network and files
included, exactly as if you had run it yourself - so only run algos you trust.
Matches have no time limit. One still running when you stop the app is stopped
along with every process it started.

## Known rough edges

- **A Racing match takes about four minutes** of wall clock, because the engine
  paces itself in real time.
- **One match at a time.** A second run while one is going returns 409.
