# Quickstart

Your bot is a web server. When a match starts, stomped opens a WebSocket to it, sends the game frame by frame, and your bot sends controller inputs back. Here's how to get one on the ladder.

## 1. Make a Melee Bot

Yeah, this is the hard part, and we can't do it for you. You need code that looks at the game and decides what to press, every frame. Some places to start:

- [slippi-ai](https://github.com/vladfi1/slippi-ai) is Phillip, the neural net that learned Melee from Slippi replays. It's open source.
- [SmashBot](https://github.com/altf4/SmashBot) is a hand-coded Fox, built on [libmelee](https://github.com/altf4/libmelee).
- The [Slippi replay spec](https://github.com/project-slippi/slippi-wiki/blob/master/SPEC.md) explains every event your bot gets to read.

The example below just walks at the opponent and presses A. Swap in your own brain.

## 2. Make a Server for It

The server has two jobs: answer `GET /ping` with `pong`, and accept a WebSocket at the same URL. Over the socket, text messages are the match steps (`character`, `ready`, `game`, `over`) and binary messages are the game itself: one in per frame, one 12-byte pad back per frame. When you see frame F, send the pad for `F + 1 + inputDelayFrames`.

<!-- lang:ts -->
```ts
// bot.ts: Marth walks at the opponent and taps A in reach
const CHARACTER = 9; // Marth; the ids are in the character table on Match Socket
const A = 0x0100;
const REACH = 10; // close enough to hit
const EVENT_PAYLOADS = 0x35; // opens the stream: the payload size of every other event
const POST_FRAME = 0x38; // one per player per frame: position, percent, stocks, action
const FRAME_BOOKEND = 0x3c; // closes a frame: time to send a pad

// i32 frame · u16 buttons · u8 stickX · u8 stickY · u8 cstickX · u8 cstickY · u8 L · u8 R, little-endian
function pad(frame: number, buttons = 0, stickX = 128): Uint8Array {
    const bytes = new Uint8Array(12);
    const view = new DataView(bytes.buffer);
    view.setInt32(0, frame, true);
    view.setUint16(4, buttons, true);
    bytes.set([stickX, 128, 128, 128, 0, 0], 6);
    return bytes;
}

class Match {
    port = 0;
    lead = 5; // having seen frame F, the pad for F + lead is the one that lands
    sizes = new Map<number, number>();
    x = [0, 0]; // where each player stands

    // a message is a run of events: a command byte, then that command's payload
    *events(msg: Uint8Array): Generator<[number, DataView]> {
        const view = new DataView(msg.buffer, msg.byteOffset);
        for (let i = 0; i < msg.length; ) {
            const cmd = msg[i];
            if (cmd === EVENT_PAYLOADS) {
                const n = msg[i + 1];
                for (let j = i + 2; j < i + 1 + n; j += 3) this.sizes.set(msg[j], view.getUint16(j + 1));
                i += 1 + n;
            } else {
                const size = this.sizes.get(cmd) ?? 0;
                yield [cmd, new DataView(msg.buffer, msg.byteOffset + i + 1, size)];
                i += 1 + size;
            }
        }
    }

    text(ws: Bun.ServerWebSocket<Match>, step: any) {
        this.port = step.port;
        this.lead = 1 + step.inputDelayFrames;
        if (step.step === "character") ws.send(JSON.stringify({ step: "character", character: CHARACTER, costume: 0 }));
        if (step.step === "ready") ws.send(JSON.stringify({ step: "ready" }));
        if (step.step === "game") {
            // the game frame names the last finished frame: cover the first `lead` frames now
            for (let f = step.frame + 1; f <= step.frame + this.lead; f++) ws.send(pad(f));
            // reconnected mid-game: the stream resumes without its header, ask for it
            if (step.frame > -124) ws.send(JSON.stringify({ step: "replay" }));
        }
    }

    binary(ws: Bun.ServerWebSocket<Match>, msg: Uint8Array) {
        if (!this.sizes.size && msg[0] !== EVENT_PAYLOADS) return; // not readable until the header
        for (const [cmd, payload] of this.events(msg)) {
            if (cmd === POST_FRAME) this.x[payload.getUint8(4)] = payload.getFloat32(9);
            if (cmd === FRAME_BOOKEND) {
                const frame = payload.getInt32(0) + this.lead;
                const dx = this.x[1 - this.port] - this.x[this.port];
                // this pad lands `lead` frames from now, and a walking pair closes about 3 units a frame
                if (Math.abs(dx) < REACH + 3 * this.lead) ws.send(pad(frame, frame % 2 ? A : 0));
                else ws.send(pad(frame, 0, dx > 0 ? 188 : 68));
            }
        }
    }
}

Bun.serve<Match>({
    port: 3000,
    fetch(request, server) {
        if (new URL(request.url).pathname.endsWith("/ping")) return new Response("pong");
        if (server.upgrade(request, { data: new Match() })) return;
        return new Response("websocket only", { status: 400 });
    },
    websocket: {
        maxPayloadLength: 64 * 1024 * 1024, // a `replay` answer is the whole game so far
        message(ws, raw) {
            if (typeof raw === "string") ws.data.text(ws, JSON.parse(raw));
            else ws.data.binary(ws, new Uint8Array(raw));
        },
    },
});
```

```sh
bun bot.ts
```
<!-- /lang:ts -->
<!-- lang:py -->
```python
# bot.py: Fox walks at the opponent and taps A in reach
import asyncio
import http
import json
import struct
from websockets.asyncio.server import serve

CHARACTER = 2  # Fox; the ids are in the character table on Match Socket
A = 0x0100
REACH = 10  # close enough to hit
EVENT_PAYLOADS = 0x35  # opens the stream: the payload size of every other event
POST_FRAME = 0x38  # one per player per frame: position, percent, stocks, action
FRAME_BOOKEND = 0x3C  # closes a frame: time to send a pad


def pad(frame, buttons=0, stick_x=128):
    # i32 frame · u16 buttons · u8 stickX · u8 stickY · u8 cstickX · u8 cstickY · u8 L · u8 R, little-endian
    return struct.pack("<iH6B", frame, buttons, stick_x, 128, 128, 128, 0, 0)


class Match:
    def __init__(self):
        self.port = 0
        self.lead = 5  # having seen frame F, the pad for F + lead is the one that lands
        self.sizes = {}
        self.x = [0.0, 0.0]  # where each player stands

    def events(self, msg):
        # a message is a run of events: a command byte, then that command's payload
        i = 0
        while i < len(msg):
            cmd = msg[i]
            if cmd == EVENT_PAYLOADS:
                n = msg[i + 1]
                self.sizes = {msg[j]: struct.unpack_from(">H", msg, j + 1)[0] for j in range(i + 2, i + 1 + n, 3)}
                i += 1 + n
            else:
                yield cmd, msg[i + 1 : i + 1 + self.sizes.get(cmd, 0)]
                i += 1 + self.sizes.get(cmd, 0)

    async def text(self, ws, step):
        self.port = step["port"]
        self.lead = 1 + step["inputDelayFrames"]
        if step["step"] == "character":
            await ws.send(json.dumps({"step": "character", "character": CHARACTER, "costume": 0}))
        if step["step"] == "ready":
            await ws.send(json.dumps({"step": "ready"}))
        if step["step"] == "game":
            # the game frame names the last finished frame: cover the first `lead` frames now
            for f in range(step["frame"] + 1, step["frame"] + 1 + self.lead):
                await ws.send(pad(f))
            # reconnected mid-game: the stream resumes without its header, ask for it
            if step["frame"] > -124:
                await ws.send(json.dumps({"step": "replay"}))

    async def binary(self, ws, msg):
        if not self.sizes and msg[0] != EVENT_PAYLOADS:
            return  # not readable until the header
        for cmd, payload in self.events(msg):
            if cmd == POST_FRAME:
                self.x[payload[4]] = struct.unpack_from(">f", payload, 9)[0]
            if cmd == FRAME_BOOKEND:
                frame = struct.unpack_from(">i", payload)[0] + self.lead
                dx = self.x[1 - self.port] - self.x[self.port]
                # this pad lands `lead` frames from now, and a walking pair closes about 3 units a frame
                if abs(dx) < REACH + 3 * self.lead:
                    await ws.send(pad(frame, A if frame % 2 else 0))
                else:
                    await ws.send(pad(frame, 0, 188 if dx > 0 else 68))


async def handler(ws):
    match = Match()
    async for msg in ws:
        if isinstance(msg, str):
            await match.text(ws, json.loads(msg))
        else:
            await match.binary(ws, msg)


def process_request(connection, request):
    if request.path.endswith("/ping"):
        return connection.respond(http.HTTPStatus.OK, "pong")


async def main():
    async with serve(handler, "0.0.0.0", 3000, process_request=process_request, max_size=None):
        await asyncio.get_running_loop().create_future()


asyncio.run(main())
```

```sh
pip install websockets && python bot.py
```
<!-- /lang:py -->

Run it, and `curl localhost:3000/ping` should say `pong`.

## 3. Put It on the Internet

stomped needs a public `https` URL for your bot. Two options:

- **Put it on a cloud box in US East.** Any VM or container host with a public `https` URL works. The arena is in Ashburn, Virginia and a pad is due 11 ms after its frame is sent, so the box should be in the same region; from further away your bot plays extra frames behind (see [Timing](/reference/match-socket/#timing)).
- **Run it at home through a tunnel.** `cloudflared tunnel --url http://localhost:3000` or `ngrok http 3000` gives you a public `https` URL pointing at your machine, WebSockets included, with your home's round trip on every pad. **Heads up: this opens a port on your personal computer to the internet.** The bot above only answers `/ping` and the socket, but make sure you know what you're exposing.

Your URL is also your bot's password, so register something unguessable like `https://your-host/7f3a9c2e-…`. The bot above answers on any path.

## 4. Register It

Sign in at [stomped.dev](https://stomped.dev), go to [Bots](https://stomped.dev/bots), paste the URL. stomped pings it and opens a socket right then, and if both work your bot is on the ladder and gets its first match within a few minutes.

## 5. Make It Good

- **Read more of the game.** The binary messages are the raw `.slp` event stream, the same bytes as the replay file. The bots above only pull out two fields. The [stream layout](/reference/match-socket/#the-game-server-bot) and the Slippi spec list everything else, and in TypeScript slippi-js's `SlpStream` parses all of it for you.
- **Don't be late.** The game runs at 60 Hz and your pad has 11 ms from when the frame was sent, so host your bot next to the arena (US East). Late pads count as neutral. See [Timing](/reference/match-socket/#timing).
- **Check the handshake** so random people can't start games on your server: [The Handshake](/reference/match-socket/#the-handshake).
- **Give it to an agent.** [/llms-full.txt](/llms-full.txt) is the whole spec and API in one file.
