Getting started

Install

curl -fsSL https://sloppy-lang.org/install | bash

In a terminal, on x86-64 or arm64. Installs to ~/.sloppy; the command works at once.

curl -fsSL https://sloppy-lang.org/install | bash

In Terminal, on a Mac with Apple Silicon (M1 or later). Installs to ~/.sloppy; no Xcode needed.

irm https://sloppy-lang.org/install.ps1 | iex

In PowerShell, on Windows 10 or 11 (x64). Installs to %LOCALAPPDATA%\sloppy; the command works at once.

On a phone or tablet? Sloppy installs on a computer; here, try it in the browser.

The installer puts Sloppy in your home directory (~/.sloppy, or %LOCALAPPDATA%\sloppy on Windows) and the sloppy command on your PATH, ready in the same terminal (when ~/.local/bin is on your PATH, as on most Linux systems; if not, the installer shows the line that makes it so). Nothing else is needed: no C compiler, no linker, no SDK or Xcode. sloppy upgrade installs newer releases.

On a phone, or an Intel Mac, Sloppy's programs run in any browser: write and run them in the playground.

A first program

Save this as hello.jo:

print("hello, world")

coins = 3
price = 1.5
print("{coins} coins at {price} each cost {coins * price}")

loop i in [1..4]:
    print("round {i}")

and run it:

sloppy hello.jo

(sloppy run hello.jo is the same.) Each run compiles the whole program, in a few milliseconds, and runs it. sloppy alone is an interactive prompt, for trying things a line at a time.

On Windows, an editor makes this simplest: VS Code with the Sloppy extension runs the open file with the run button at the top right, or Ctrl+F5. With Notepad, choose "All files" under "Save as type" (or it saves hello.jo.txt), and keep the encoding UTF-8; then in Explorer, right-click the folder and pick "Open in Terminal" to type the command there. PowerShell's > and Out-File write UTF-16, which Sloppy does not read as a program: save files from an editor, or with Set-Content -Encoding utf8.

A name is given a value with =, and {...} inside text puts a value there. loop i in [1..4]: runs the indented line once for each number from 1 to 4.

New to programming? Make a game starts from an empty window and explains each thing as it comes up; the rest of the documentation is written for people who have programmed before.

A first game

A program with update and draw functions is a game: it opens a window and calls them every frame, update with the seconds since the last frame.

pos = vec2(400, 300)

update = (dt: f64):
    pos += input_axis() * 300 * dt

draw = ():
    clear(rgb(0.08, 0.08, 0.12))
    circle(pos, 24, rgb(1.0, 0.6, 0.2))
    text("arrow keys or W A S D", vec2(20, 20), 24, WHITE)

Save it as game.jo, then:

sloppy game.jo           # in a window
sloppy watch game.jo     # the same, reloaded each time you save: change a color and look
sloppy --web game.jo     # in your browser

Starting from a template

sloppy new makes a directory with a program to start from, which runs as it is:

sloppy new my_game            # the smallest game: a window, update and draw
sloppy new my_game arcade     # a 2D arcade game: a title menu, a score, a best score kept, sounds
sloppy new my_game pico       # PICO-8's style: 128 x 128 pixels, 16 colors, a pixel font, sprites as text
sloppy new my_game platformer # a 2D platformer: a level written as text, slopes, platforms, coins
sloppy new my_game 3d         # a first-person 3D game: mouse look, walking, jumping, shooting
sloppy new my_game character  # an animated glTF character, follow camera and pause menu (no downloads)
sloppy new my_tale story      # a story in lines and choices (a visual novel), its script as Ren'Py's
sloppy new my_duel online     # two players anywhere, no server: invite a friend by a link (rollback)
sloppy new my_room room       # 2-4 players by a room link, rollback, rejoin on reload
sloppy new my_tool program    # a program for the terminal, with a test
sloppy new my_list tui        # a program for the whole terminal: a list of things to do (keys, the mouse)
sloppy new my_site server     # a web server: a JSON API kept in a file, a page, live updates, a test
sloppy watch my_game/my_game.jo

For imported 3D characters, materials and a sky panorama, start with the complete animated glTF scene. It shows asset embedding, model scale, animation crossfades and a follow camera. Add a pause/settings screen with responsive layout; its buttons and value controls support mouse, touch, keyboard and gamepad navigation.

Sharing it

sloppy build game.jo                       # game (game.exe on Windows): a program for this system
sloppy build game.jo --target windows      # game.exe, from any system
sloppy build game.jo --target wasm         # game.html: one file that runs in any browser
sloppy build game.jo --target wasm -o game.zip   # the same, ready for itch.io

On itch.io: make a project of kind HTML, upload game.zip, tick "This file will be played in the browser", and give the viewport the size of your window(...) (1280 x 720 if it has none); "Fullscreen button" lets players make it bigger. Give the game a name in its build block (build: and name = "Drone Arena" below it): what save_data keeps is stored under it, and games on one site share the browser's storage (it is the browser's localStorage, as sloppy:<name>/<key>, the bytes in base64). Sound starts after the player's first click, tap or key, as browsers require, and stops while the tab is hidden (the game gets no frames then). A file the game reads is built in with embed("x.png") or embed_dir("assets"): a page has no disk. Debug builds are the smaller ones; --release makes the code faster and larger.

A big game (many megabytes of assets) for a web site: sloppy build game.jo --target wasm --wasm-file writes game.html and game.wasm beside it. The page is small and the browser compiles the program while it downloads, so the game starts sooner and the page holds less memory (a 19 MB program: its page is parsed in 0.15 s instead of 0.7 s). Put both files on the server (-o game.zip --wasm-file zips both, for itch.io). Browsers do not let a page opened from disk load a file beside it, so that page needs a web server (python3 -m http.server in its folder, to try it); without --wasm-file the page is one file that works anywhere.

A panic or a load error is written to the page's #log element. A page with its own overlay over the game (a loading screen, say) can hear of it too: window.addEventListener("sloppy:error", (e) => show(e.detail)), the event's detail being the error's text.

Pause when window_focused() is false: the player clicked outside the page's frame (sloppy new makes games that do). The page takes the keyboard as it loads.

On phones (tick "Mobile friendly" on itch.io, and pick the orientation) games work with fingers: Phones below says how to lay one out.

Each is one file with nothing to install alongside it (--target macos and --target linux make the same from any system too; a Windows build's .pdb beside it is for debuggers only, so leave it out of what you share; Windows warns about a program it has not seen signed before, "More info", then "Run anyway"). sloppy build game.jo --target macos -o Game.app makes a Mac app (its icon, its name in the Dock and the menu bar); zip -r Game.zip Game.app to share it. It is not signed by an Apple developer account, so a Mac opens a downloaded one after a right click, Open (or System Settings, Privacy & Security, Open Anyway).

Phones

The first finger is the mouse, its left button down while it touches, so a game made for the mouse works as it is; touches() has every finger (on-screen buttons: left, right, jump), and touch_ids() a number for each that stays the same while it is down (a drag that turns a camera: how far that finger moved since the last frame). touch_device() says the screen is a touch screen from the start, touch_input() that the last input was a finger (no hover then). swipe() is the way a drag just went (a 2048 move), long_press() a finger held still. toggle_fullscreen() from a tap goes fullscreen as the finger lifts (browsers allow it only then); iPhones' Safari has no fullscreen for a page's canvas (can_fullscreen() says so).

A design size. For a game held upright, give window a phone's shape in points, as window("Merge", 360, 640): phones are 360 to 430 points wide, and taller than 640, so with the default screen_fit(.expand) the extra height shows; visible_rect() is all of it. Lay out from its edges: a header at its top, the board in the middle, buttons at its bottom. css_pixel() is how large a point (a CSS pixel: about 1/160 inch on a phone) is in your units, so 48 * css_pixel() is a button a finger hits on any screen; pixel_ratio() is the screen's pixels per point.

Held the other way, and on a desktop. A game made taller than wide shows a note to turn the phone upright while it is held sideways (upright_hint(false) for one laid out for both ways), and one made wider than tall the other way round (sideways_hint(false)). On a desktop browser the same 360 x 640 column shows in the middle of a wider screen, scaled to its height. A game laid out for both shapes can change its units as the screen turns: design_size(w, h) (or window(...) called again) at the start of update:

update = (dt: f64):
    p = pixel_size() / f32(pixel_ratio())       # the screen, in points
    if p.y > p.x: design_size(360, 640) else: design_size(800, 450)

Or draw a column designed at 360 x 640 under camera2d_fit(Rect(0, 0, 360, 640), visible_rect()): menus and hud_ boxes take taps where they show, under any 2D transform.

The notch and the home bar. safe_rect() is the part of visible_rect() that a phone's notch, rounded corners and home bar leave clear (all of it elsewhere): backgrounds over visible_rect(), buttons and text inside safe_rect(). The page around the game takes the color the game clears the screen with.

Taps, lists and menus. Buttons act as the finger lifts, on the button it went down on; a finger that slides away is no tap, so a drag that starts on a row of a hud_scroll list scrolls the list (it glides on when let go moving) and buys nothing. ui_ menus on a touch screen draw each item as a box no wider than the screen (ui_style.margin from its edges), with no keyboard focus marks.

The keyboard. A ui_text_field or hud_text_field tapped brings up the phone's keyboard, with a Paste button beside what is typed; the page moves up over the keyboard as far as the field needs (the game keeps its size), and when the player puts the keyboard away the field lets go of it. ui_typing() says a field has the keyboard.

Trying it on the desktop. A native run takes a phone's shape and a finger's input: SLOPPY_WINDOW=360x800 sloppy run game.jo opens a phone-shaped window, SLOPPY_TOUCH=1 makes it a touch screen (menus as on a phone, the turn-the-phone notes) and SLOPPY_PIXEL_RATIO=3 its pixels per point; SLOPPY_INPUT="5:touch1=180x300 7:touch1-" taps (in your units), and with SLOPPY_SCREENSHOT=out.png SLOPPY_FRAMES=10 saves the frame. In a browser, the developer tools' device mode shows a phone, its rotation and its touches.

A board and buttons for a phone held either way: the board in the part of the screen the buttons leave (camera2d_fit), a tool picked with a button, then a tap on the board; a tap on a button is not one on the board (hud_hovered()):

tool = 0
update = (dt: f64):
    if mouse_pressed(.left) and not hud_hovered():
        cell = screen_to_world(mouse_pos()) / 64.0          # (the board: cells of 64)
        place(tool, int(cell.x), int(cell.y))
draw = ():
    global tool
    clear()
    v = visible_rect()
    upright = v.h > v.w
    board = if upright: Rect(v.x, v.y, v.w, v.h - 160) else: Rect(v.x, v.y, v.w - 220, v.h)
    camera2d_fit(Rect(0, 0, COLS * 64, ROWS * 64), board)
    draw_board()
    reset_transform()
    loop i in 0.. and name in ["Gun", "Frost", "Cannon"]:
        r = if upright: Rect(v.x + 20 + f64(i) * 150, v.y + v.h - 140, 140, 120) else: Rect(v.x + v.w - 200, v.y + 20 + f64(i) * 130, 180, 120)
        if hud_button(r, name, selected = tool == i): tool = i

Editors

The Sloppy extension for VS Code, Cursor and VSCodium (also on Open VSX) has highlighting, errors as you type, completion, hover, go to definition and rename, and commands to run a file:

code --install-extension RedFoxLabs.sloppy

For other editors, sloppy lsp is a language server: the README shows Neovim and Helix.

Scripts and tools

Sloppy is for programs without a window too: sloppy new my_tool program makes a command-line program with a test to start from, and sloppy my_tool.jo a b runs it with args() being ["my_tool.jo", "a", "b"]. A function named main runs after the top-level code (or where the file calls it).

#!/usr/bin/env sloppy
# count.jo: lines and words in files, largest first

struct Options:
    words = false               # count words too
    top = 0                     # only the largest n (0: all)
    files: str[]                # the arguments that are not options

main = () -> int:
    opts = parse_args[Options]("lines (and words) in files, largest first")
    if opts.files.len() == 0:
        eprint("count.jo: which files? (count.jo --help)")
        return 2                                  # main's int is the exit code
    rows: (str, int, int)[]
    failed = false
    loop path in opts.files:
        if let f = open_file(path):               # line by line: any size of file
            defer f.close()
            n_lines = 0
            n_words = 0
            loop:
                got = f.read_line()
                if got is FileError:
                    eprint("count.jo: cannot read {path}: {got.message}")
                    return 1
                if got == none: break
                line = got!
                n_lines += 1
                if opts.words: n_words += split(line).len()
            rows.push((path, n_lines, n_words))
        else:
            eprint("count.jo: cannot open {path}: {file_error()}")
            failed = true
    rows.sort((r): r.1, descending = true)
    if opts.top > 0 and rows.len() > opts.top: rows.resize(opts.top)
    loop r in rows:
        if opts.words: print("{r.0:<30} {r.1:>8} {r.2:>8}")
        else: print("{r.0:<30} {r.1:>8}")
    if failed: 1 else: 0

With the first line #!/usr/bin/env sloppy and chmod +x count.jo, it runs as ./count.jo -w --top 3 *.txt (on Linux and macOS). Everything after the file's name goes to the script, --release too; args()[0] is the script's own path (exe_path() is where its build is kept). parse_args reads the options into the struct: a bool field is a flag, others take a value, the last list field gets the other arguments, and --help lists them all, each beside its field's comment (-w, --words count words too: the comment need not name the option); a mistake (--top many) is said with that help, and exit code 2.

Handling errors in scripts

Reads, regex(pattern) and ints(text) return a value or an error. Test the error with is; after an early return, the value has its successful type. if let and ! handle optionals (none), so they do not replace this check. Use .unwrap() for input you trust: it stops the program if the operation fails.

# A user-supplied pattern: report it without a panic.
main = () -> int:
    argv = args()
    if argv.len() != 2:
        eprint("usage: search.jo PATTERN")
        return 2
    pattern = regex(argv[1])
    if pattern is RegexError:
        eprint("pattern character {pattern.position}: {pattern.message}")
        return 2
    loop let line = read_line():
        if line.find(pattern) != none: print(line)
    0

In a helper, ? passes an error back to the caller. Write that error in the helper's return type, then handle it once in main:

read_numbers = (path: str) -> int[] | FileError | ParseError:
    text = read_file(path)?
    ints(text)?

? also passes on none. For read_line(file), check FileError, then none for EOF, then use the line, as in count.jo above; read_line(file)? would return on EOF too. For an interactive prompt, loop let line = input("next> "): print(line) ends at EOF (or browser cancellation); an empty line is still a value. See errors and propagation for the full rules.

A program can also take the whole terminal, as a screen of characters it draws on (a file browser, an editor, a game in the terminal): import term, term.start(), then term.put(x, y, text, fg = term.YELLOW), term.box(...) and term.flush(), which writes only what changed, and term.read_event() for keys, the mouse and resizes. The terminal is put back as it was however the program ends. sloppy new my_list tui starts one; terminal programs says the rest, and examples/files.jo is a file browser.

Fetching from the web

net.fetch(url) (after import net) asks a web server for what is at an address and gives an HttpReply: its status (200 when all went well, 0 when no reply came, and why says why), text, data (the same as bytes), headers and size. JSON goes straight into a struct of yours with from_json[T], which reads the fields the struct has and skips the others:

import net

struct Repo:
    full_name = ""
    stargazers_count = 0
    description: str? = none          # null in the JSON is none

r = net.fetch("https://api.github.com/repos/python/cpython")
if r.status != 200:
    eprint("no: {r.status} {r.why}")
    exit(1)
repo = from_json[Repo](r.text)
if repo is TextError:
    eprint("not what was expected: {repo.message}")
    exit(1)
print("{repo.full_name}: {repo.stargazers_count} stars, {repo.description ?? "-"}")

```gdscript import net

urls = [loop id in [1..50]: "https://api.example.com/items/{id}"] rs = net.fetch_all(urls, at_once = 8, wait = 10.0) loop i in 0.. and r in rs: if r.status != 200: eprint("{urls[i]}: {r.status} {r.why}") ```

Writing a server

import http serves web pages, an API, or a game's page with its WebSockets, from a native program. Each route is a method and a path, with :names for the parts that vary, answered by a function from a Request to a Response:

import http

struct Todo:
    id = 0
    title = ""
    done = false

struct TodoIn:
    title = ""

todos: Todo[]

http.get("/todos", (r: http.Request) -> http.Response: http.json(todos))
http.get("/todos/:id", (r: http.Request) -> http.Response:
    id = to_int(r.params["id"]) ?? -1
    loop t in todos:
        if t.id == id: return http.json(t)
    http.json_error(404, "no todo {id}"))
http.post("/todos", (r: http.Request) -> http.Response:
    t = TodoIn()
    if let bad = http.read_json(r, t): return bad     # 400, saying what is wrong with the JSON
    todos.push(Todo(todos.len() + 1, trim(t.title)))
    http.json(todos.last(), 201))
http.files("/", "public")                             # the rest: the files under public/

http.log_requests = true                              # a line for each, with its time, on standard error
if not http.serve(8080): eprint("port 8080 is taken")
on_quit = (): write_file("todos.json", to_json(todos))

``gdscript http.listen(8080, host = "127.0.0.1") spawn((): http.serve(8080), background = true) # (the program's end does not wait for it) r = net.fetch("http://127.0.0.1:8080/todos") # answered meanwhile assert(r.status == 200)

```gdscript import http import net

http.get("/ws", (r: http.Request) -> http.Response: if r.headers.get("origin") != "https://chat.example": return http.status(403) http.websocket(r)) http.files("/", "public")

# a peer's own task: it joins the room its page asked for (/ws?room=lobby), and what it sends # goes to everyone in that room chat = (p: int): room = net.handshake(p).query.get("room") ?? "lobby" net.join_room(p, room) net.send_room(room, "{net.members(room).len()} here") loop not net.gone(p) and not stopping(): loop e in net.receive([p], wait = 30.0): if e.kind == .message: net.send_room(room, e.text)

# each peer that connects, given a task of its own take_peers = (): loop not stopping(): p = net.accept(wait = 1.0) if p >= 0: spawn((): chat(p))

spawn(take_peers, background = true) http.serve(8080) ```

``gdscript listeners: int[] http.get("/events", (r: http.Request) -> http.Response: listeners = listeners.filter((c: int): http.stream_open(c)) listeners.push(r.conn) http.events()) # ... when something happens (a booking, a score): listeners = listeners.filter((c: int): http.send_event(c, to_json(score), event = "score", id = "{score.id}"))

A stream sent nothing for 15 seconds is sent a comment, which the page skips (http.heartbeat), so that a proxy does not cut it for being idle; at most 1000 are open at once (http.most_streams), and a stop (SIGTERM) ends them as a stream ends. A page that connects again says the id of the last event it had in r.headers.get("last-event-id"): what came since can be sent first. Lines of data are each a data: line of their own, so text from a client cannot start an event of its own.

On a server of its own. Listen on host = "127.0.0.1" and put Caddy in front: it gets the certificate (https) and passes requests on. Running a matchmaking server sets this up on a small droplet, with a systemd service that starts the program and restarts it; for a site of your own the Caddyfile is

example.org {
    reverse_proxy 127.0.0.1:8080
}

(WebSockets pass through it too; encode gzip on a line of its own in the block has Caddy gzip what the program does not, and leaves what it did.) Behind Caddy, r.address (and net.handshake(p).address for a WebSocket, and the log's lines) is Caddy's, 127.0.0.1, unless the program says Caddy is a proxy it trusts: http.trust_proxy = ["127.0.0.1"]. Then a request from it has the client's address, the last in the X-Forwarded-For header that Caddy adds to (what comes before that in it is the client's to write, and is not taken). Without a proxy in front, leave trust_proxy empty, as it is unless set: anyone could send the header saying anything. With https, http.secure_cookies = true too.

A systemd service for it, /etc/systemd/system/todos.service:

[Unit]
Description=todos
After=network-online.target

[Service]
User=todos
WorkingDirectory=/srv/todos
ExecStart=/srv/todos/todos
Restart=always
RestartSec=2
MemoryMax=512M

[Install]
WantedBy=multi-user.target

WorkingDirectory matters: http.files("/", "public"), read_file("todos.json").unwrap() and the like are relative to it (without it, to /). MemoryMax has systemd stop a program that grows past it (and Restart start it again), rather than the machine running out. systemctl stop sends SIGTERM, which http.serve answers by finishing what it is answering (up to drain seconds) and returning.

Keeping data. A small server keeps its data in a JSON file: to_json, written with write_file(path, text, sync = true), and from_json[T] reads it back at the start. sync writes a new file beside it, has it put on the disk itself, and only then has it take the old one's place, so that neither a crash nor a power cut leaves half a file, or none (a plain write_file survives the program being killed, not the machine losing power).

Writing the whole file at each change costs time as it grows: a booking site went from 320 bookings a second to 120 at 2,000 records. Past a few hundred, keep each change as a line at the end of a log, on the disk before the answer goes, and write the whole file only now and then:

struct Booking:
    id = 0
    name = ""
struct Db:
    seq = 0                     # the last change written into it
    bookings: Booking[]
struct Change:
    seq = 0
    booking = Booking()

db = Db()

# a change: made, then one line at the end of the log (a few milliseconds)
add = (b: Booking) -> bool:
    global db
    db.seq += 1
    db.bookings.push(b)
    append_file("changes.log", to_json(Change(db.seq, b)) + "\n", sync = true)

# at the start: the whole file, then the changes after it (a line cut short by a power cut
# does not read, and is left out), and the whole file written again, the log emptied
load = ():
    global db
    text = read_file("data.json")
    if text is str:
        got = from_json[Db](text)
        if got is TextError:
            eprint("cannot parse data.json: {got.message}")
            exit(1)
        db = got
    else if file_exists("data.json"):
        eprint("cannot read data.json: {text.message}")
        exit(1)
    changes = ""
    log = read_file("changes.log")
    if log is str: changes = log
    else if file_exists("changes.log"):
        eprint("cannot read changes.log: {log.message}")
        exit(1)
    loop line in split(changes, "\n"):
        c = from_json[Change](line)
        if c is Change and c.seq > db.seq:
            db.seq = c.seq
            db.bookings.push(c.booking)
    write_file("data.json", to_json(db), sync = true)
    write_file("changes.log", "", sync = true)

(Each line says which change it is, so that one already in the file, after a crash between the two writes, is not made twice.) Another way is a file for each thing, bookings/42.json, each written whole as it changes.

A file only ever written with sync is whole whenever it is read, so a backup is a copy of it at any time (cp todos.json backups/todos-$(date +%F).json from cron). The server keeps the data in memory and writes all of it at each change: another program that changes the file while it runs (a command to add a user) has its change written over at the next save. Make such changes through the server, as a route only an admin can call, or stop the server first (systemctl stop todos, the command, systemctl start todos).

For more data than fits in memory, or changes from more than one program, import sqlite: one file, read and changed a row at a time, with the values for its ?s given apart from the SQL (never put a client's text in the SQL itself):

import sqlite

struct Todo:
    id = 0
    title = ""
    done = false

db = unwrap(sqlite.open("todos.db"))
if let e = db.exec("CREATE TABLE IF NOT EXISTS todos (id INTEGER PRIMARY KEY, title TEXT, done BOOL)"): panic(e.message)
added = unwrap(db.run("INSERT INTO todos (title, done) VALUES (?, ?)", ["milk", false]))
todos = unwrap(db.query[Todo]("SELECT * FROM todos WHERE done = ?", [false]))

A row's columns go into the struct's fields of the same names; db.begin() and db.commit() make changes that belong together one. A backup of a database another program has open is sqlite3 todos.db ".backup backups/todos.db", not a copy of the file.

Rhythm games and music sync

A rhythm game keeps its notes on the music's clock, not the frames': audio_time() is the seconds of sound heard so far. It is smooth: between mixes it runs on the monotonic clock, kept in step with what the output says it has played (averaged over its last reports, so a device that reports a 10 ms period at a time gives a clock off a straight line by about 0.2 ms); it never goes back and never passes the sound mixed. The output's own delay is in it, as far as the system reports one. It starts with the sound: the first play, play_music, audio_time() or audio_started(); in a web page at the first click or key (browsers allow no sound before: audio_started() says when). With no sound device it moves with the frames' time, a frame at a time, and in a screenshot run exactly 1/60 s a frame, so tests come out the same each run.

# four lanes: notes fall to a line, hit as they cross it
window("Lanes", 800, 600)
song = load_music(embed("song.ogg")).unwrap()
chart = [(0, 1.0), (1, 1.5), (2, 2.0), (3, 2.25), (0, 2.5)]   # (lane, seconds into the song)
keys = [Key.d, Key.f, Key.j, Key.k]
hit = fill(false, chart.len())
offset = load_data("offset") ?? "0"     # the player's calibration (seconds), from a settings screen
calib = to_float(offset) ?? 0.0
start = audio_time() + 1.0                # the song starts a second from now, to the sample
music = play_music(song, looping = false, at = start)

# the song's time when the player heard what was playing at audio time t
song_time = (t: f64) -> f64: t - start - calib

update = (dt: f64):
    loop lane in 0.. and k in keys:
        # (each press this frame, two in one frame too, at the time the desktop gave it)
        loop i in [0..key_presses(k)):
            judge(lane, song_time(audio_time_at(key_press_time(k, i))))

judge = (lane: int, t: f64):
    loop j in 0.. and n in chart:
        if hit[j] or n.0 != lane: continue
        if abs(t - n.1) < 0.05:                # 50 ms either way
            hit[j] = true
            print("lane {lane}: {(t - n.1) * 1000.0:.0} ms")
            return

draw = ():
    clear(BLACK)
    now = song_time(audio_time())
    rect(0, 500, 800, 4, WHITE)                # where notes are hit
    loop j in 0.. and n in chart:
        if hit[j]: continue
        y = 500.0 - (n.1 - now) * 400.0        # 400 units a second
        rect(f64(100 + n.0 * 160), y - 10.0, 120, 20, CYAN)

Starting on time. play(s, at = t) and play_music(m, at = t) start a sound when audio_time() is t, to the sample, whatever the frame rate (Unity's PlayScheduled). Give it a little ahead: the mixer works audio_latency() ahead of what is heard (20 to 100 ms), and an at already mixed starts at once, as far into the sound as it would be by then (a song resumed with at = audio_time() - 30.0 is 30 seconds in, in time with the clock). A metronome schedules each click half a second before it:

click = tone(1800.0, 0.03, .square, 0.3)
beat = 60.0 / 120.0                         # 120 beats a minute
next_click = audio_time() + 0.5
update = (dt: f64):
    global next_click
    loop next_click < audio_time() + 0.5:
        play(click, at = next_click)
        next_click += beat

Coming from Scratch

A Scratch project is sprites, each with its scripts running at once. In Sloppy one program holds them all: update runs every frame (Scratch's "forever" for everything at once) and draw shows what each thing looks like. sloppy new my_game arcade is a whole game to start from.

ScratchSloppy
when green flag clickedthe lines at the top of the file run first, once
foreverupdate = (dt: f64):, which the game runs every frame (dt: the seconds since the last)
a sprite, its x and ya variable for where it is, cat = vec2(240, 300), and draw drawing it there: sprite(cat_picture, cat)
costumesa few pictures, load_texture(embed("cat1.png")).unwrap(), and which one is drawn
backdropsa picture drawn first in draw, before the sprites
when key pressed, key pressed?if key_pressed(.space): (just pressed) or if key_down(.right): (held), in update
change x by 10cat.x += 10 (each frame: cat.x += 300 * dt moves 300 a second)
go to x: y:cat = vec2(100, 200); random position: vec2(random(0, 1280), random(0, 720))
glide 1 secs tomove = tween(cat, vec2(600, 300), 1.0), then move.update(dt) and cat = move.value()
touching?overlaps(Rect(...), Rect(...)) or circles_overlap(a, 20, b, 20); touching a color: img.get(x, y) of the picture
clonesa list of things: apples: Apple[], apples.push(Apple(pos)), a loop mut a in apples: to move them
delete this clonemark it (a.gone = true) in the loop, then apples.retain((a): not a.gone)
broadcast / when I receivea function, called where the message would be sent: level_up()
wait 1 secondsa timer counted down in update, or Actions: steps.then(1.0, (): say_next())
say Hello! for 2 secondsa variable for what is said and a timer; draw it with text beside the sprite
ask and waithud_text_field(...), a box to type in
pick random 1 to 10random_int(1, 11) (the top is left out), random(0.0, 1.0) for a fraction
variables, listsscore = 0 at the top; names: str[] = [], names.push("Ada")
pena picture drawn into and never cleared: pen = render_target(1280, 720) at the top; in draw, draw_to(pen), the line or dot, draw_to_screen(), then after clear, draw_target(pen)
soundsmeow = load_wav(embed("meow.wav")).unwrap() at the top, play(meow) when it should sound

Coming from p5.js, Processing or Shadertoy

p5Sloppy
setup(), draw()the lines at the top of the file run once; draw = (): each frame (and update = (dt: f64): before it, to change things)
createCanvas(800, 600)window("title", 800, 600)
background(20), fill, stroke, strokeWeightclear(rgb(0.08, 0.08, 0.08)); each shape takes its color and thickness: circle(p, 20, RED), line(a, b, 2, WHITE), ring(p, 20, 2, c)
colors 0 to 255, colorMode(HSB, 360)each part 0 to 1: rgb(1, 0.5, 0), hex(0xff8000), hsv(200.0 / 360.0, 0.8, 0.9)
ellipse, rect, line(x1, y1, x2, y2)ellipse(center, radii, c), rect(x, y, w, h, c), line(vec2(x1, y1), vec2(x2, y2), width, c)
beginShape(), vertex(x, y), endShape()a list of points: polygon(pts, c), polyline(pts, width, c)
push(), translate, rotate, pop()push_transform(), translate(x, y), rotate(a), pop_transform()
mouseX, mouseIsPressed, keyIsDown(LEFT_ARROW)mouse_pos().x, mouse_down(.left), key_down(.left)
width, height, frameCount, millis()screen_width(), screen_height(), frame_number(), elapsed() (seconds)
map(x, a, b, c, d), constrain, dist, lerpremap(x, a, b, c, d), clamp, distance, lerp
random(a, b), randomGaussian(), noise(x, y, z)random(a, b), random_normal(mean, sd), noise(x), noise(x, y), noise(x, y, z) (each 0 to 1), fbm(x, y)
TWO_PI, radians(45)TAU, 45deg
background(0, 10) for trailseach frame starts black: draw into a picture that is kept, canvas = render_target(1280, 720) with draw_to(canvas), a see-through rect over it, then draw_to_screen() and draw_target(canvas)
saveCanvas()save_png("art.png", screenshot()), then download_file("art.png"): a web page's browser downloads it
a Shadertoy shadera fragment function over a full-screen rect, as below: its iTime, iResolution and iMouse are fields you give it each frame
struct Toy:
    time: f32
    res: vec2
toy_fs = (p: Pixel2D, u: Effect2D[Toy]) -> vec4:
    uv = p.pos.xy / u.params.res                  # 0 to 1, from the bottom left
    t = u.params.time
    vec4(cos(vec3(t, t, t) + vec3(uv.x, uv.y, uv.x) * 6.0 + vec3(0, 2, 4)) * 0.5 + vec3(0.5, 0.5, 0.5), 1)
toy = make_shader(shader(effect_vs, toy_fs))

draw = ():
    use_effect(toy, Toy(f32(elapsed()), pixel_size()))
    rect(0, 0, 1280, 720, WHITE)
    no_effect()

Shader functions are Sloppy functions, and the GPU runs them (the CPU too, without one): GLSL's sin, cos, fract, floor, pow, step, smoothstep, mix, abs, min and max work on vectors' parts as there; post_effects() adds bloom and a vignette to 2D drawing as well as 3D.

Coming from JavaScript

JavaScriptSloppy
let x = 0x = 0 (whole numbers stay whole: x = 0.0 for one that holds fractions)
for (let i = 0; i < n; i++), while (x > 0)loop i in 0..n: (0 to n - 1), loop x > 0:
const xs = [1, 2] then xs.push(3)xs = [1, 2]: a const never changes, its elements neither
objects {name: "Drone", cost: 10}struct Item: with name: str and cost: f64, made as Item("Drone", 10); a map's values are all one type
` cost: ${x} , x.toFixed(2), toLocaleString()`"cost: {x}", "{x:.2f}", "{x:,}"; "{x:.2e}" for 1.50e+45
===, null, undefined==, none (a T? may be none: x ?? default, if let v = x:)
x?.y(x ?? default).y, or if let v = x: v.y (x?.y is not optional chaining: x? returns the none from the function)
try/catch, throwa function gives back what went wrong as a value (-> Item | LoadError, with error struct LoadError:); the caller checks if r is LoadError:, or passes it on with item = load(p)?
xs.map(f), filter, reduce((a, b) => a + b, 0)xs.map(f), xs.filter(f), xs.reduce(0, (a, b): a + b), sum(xs)
JSON.stringify, JSON.parseto_json(x), from_json[Item](s) (into a struct), parse_json(s)
res.json({ok: true, id})http.json({"ok": true, "id": id}) (a literal where a Json goes is one)
localStoragesave_value("save", state) and state = load_value("save", State())
setInterval(f, 30000), setTimeoutif every(1, 30.0): f() in update; Actions for steps one after another
Date.now()unix_time() (seconds since 1970: what to save to work out time away)
Phaser's this.tweens.add({...}), onCompletet = tween(from, to, 0.3, ease = ease_out_back) in a variable or field; each frame t.update(dt), t.value(), and t.done() for what comes next
a timeline / tween chainhop = chain([tween(a, b, 0.2), tween(b, a, 0.3)]): one after another, hop.value(), hop.done(); done(tweens) for a set started together
switch (s.kind), case "rect": on a tagged unionenum Shape: with circle(r: f64) and rect(w: f64, h: f64); match s: with .rect(w, h): (and a condition: .rect(w, h) if w == h:), if s is .rect:, if let .rect(w, h) = s:
scenes, this.scene.start("Level")enum Screen: title, play, over, screen = .play, and a match screen: in update and in draw
async/await, a chain of animationsa phase for each step (enum Phase: idle, swapping, clearing, falling), moved on in update when its tweens are done; or Actions for timed steps
btoa, atobbase64_encode(bytes(s)), base64_decode(s)
Express: app.get("/todos/:id", ...), app.listen(8080)http.get("/todos/:id", handler), http.serve(8080) (writing a server)
Express middleware, cors(), compression()http.before(f) (may answer early: a sign-in, a rate limit) and http.after(f); http.cors(["https://example.com"]); gzip is on (http.gzip = false)
Socket.IO: io.on("connection"), socket.join(room), io.to(room).emit(...)http.websocket(r) in a route, then net.accept and net.receive([p], wait = 30.0) in a task for each (or one loop over net.receive_server()); net.join_room(p, room), net.send_room(room, text, except = p), net.members(room)
socket.disconnect(), a close codenet.close(p, 4001, "the room is full"): the other side's .left event has e.code and e.text, a page's WebSocket event.code and event.reason
Socket.IO's reconnectiona netplay client's c.reconnect = true (1, 2, 4... up to 30 s between tries); with net alone, net.connect again when .left comes
bcrypt.hash, crypto.timingSafeEqualcrypto.hash_password(pw), crypto.check_password(pw, stored), crypto.constant_time_equal(a, b)
JSON keys that are keywords ({"when": ...})a field named when_: to_json and from_json call it "when"
window.onbeforeunloadon_quit = (): ..., which the game calls as it closes
<input type="file">, Electron's dialog.showOpenDialog, a drop zoned = open_file_dialog([".txt"]), then if let paths = file_dialog_result(d): each frame; dropped_files()
CSS cursor: pointer, cursor: col-resizeset_cursor(.hand), set_cursor(.resize_ew)
a page that redraws only as things changeredraw_on_input(): frames only on input; request_redraw() while something animates
Number.isFinite, Infinity, break_infinity.jsis_finite(x), INF (floats reach about 1.8e308); past that, use big: dust = big(1.5, 400)

Coming from React or Electron: desktop tools

A tool is a program like a game: draw runs each frame and draws its boxes, each of which says what was done to it. There is no tree of components to keep in step with the data: the data is drawn as it is, every frame. Three lines make a window behave as a desktop program's: screen_fit(.native) (units are the desktop's pixels, and a wider window shows more, laid out from visible_rect()), redraw_on_input() (frames only when something happens, so an idle tool takes no CPU) and on_quit to save.

struct Note:
    title: str
    body: str

window("Notes", 900, 600)
screen_fit(.native)
redraw_on_input()
notes = load_value("notes", [Note("First", "")])
at = 0
query = ""

on_quit = (): save_value("notes", notes)

draw = ():
    global at, query
    clear(rgb(0.11, 0.12, 0.14))
    if shortcut(.n):
        notes.push(Note("Untitled", ""))
        at = notes.len() - 1
    if shortcut(.f): hud_focus("search")
    v = visible_rect()
    query = hud_text_field(Rect(10, 10, 220, 30), query, id = "search", hint = "Search")
    y = 50.0
    loop i in 0.. and n in notes:
        if len(query) > 0 and not lower(n.title).contains(lower(query)): continue
        if hud_button(Rect(10, y, 220, 32), n.title, selected = i == at, align = .left): at = i
        y += 36.0
    notes[at].title = hud_text_field(Rect(240, 10, v.w - 250, 30), notes[at].title, id = "title")
    notes[at].body = hud_text_area(Rect(240, 50, v.w - 250, v.h - 60), notes[at].body, id = "body")
React / ElectronSloppy
useState, props, re-renderingplain variables; draw shows them as they are each frame
<input value onChange>, <textarea>name = hud_text_field(r, name), body = hud_text_area(r, body)
<button onClick>, a checkbox, a range inputif hud_button(r, "Save"): save(), on = hud_checkbox(r, "Sound", on), v = hud_slider(r, v, 0, 1)
autoFocus, ref.focus(), Tab order, Enterhud_focus("search"), Tab goes in drawing order, hud_submitted()
a scrolling <div>off = hud_scroll(r, content_height, "list"), then clip(r) ... no_clip()
a modal dialoghud_panel(visible_rect(), rgba(0, 0, 0, 0.5)) then the dialog's boxes, drawn last
drag and drop in a listclaim_press() when a row is pressed, then follow mouse_pos()
CSS (theme, font size)hud_style.button = ..., hud_style.text_size = 18.0
cursor: pointerset_cursor(.hand) (text fields show an I-beam themselves)
keyboard shortcutsif shortcut(.s): save() (Ctrl+S, Cmd+S on a Mac)
dialog.showOpenDialog, a file <input>, drop eventsd = open_file_dialog(["csv"]), then file_dialog_result(d) each frame; dropped_files()
fs.readFile, fs.writeFileread_file(path).unwrap(), write_file(path, s); in a page, download_file(path) to hand a file over
localStorage, electron-storesave_value("notes", notes), load_value("notes", default) (a file natively, the browser's storage in a page)
navigator.clipboardclipboard(), set_clipboard(s) (text fields do Ctrl+C/X/V themselves)
window.onbeforeunloadon_quit = (): ...
requestAnimationFramedraw itself; with redraw_on_input(), request_redraw() or redraw_after(s) asks for a frame

Coming from Python

PythonSloppy
def f(a, b):f = (a: int, b: int) -> int: ...
for i in range(n):, range(1, n + 1), xs[2:5]loop i in 0..n:, loop i in [1..n]: (] keeps the end), xs[2..5]
while x > 0:loop x > 0:
[w.upper() for w in ws if w][loop w in ws: if w != "": w.upper()]
f"{x:.2f}", "{:.2f}".format(x)"{x:.2f}": every string puts values in; r"..." does not (a regular expression's {4})
7 // 2, 7 / 27 / 2 is 3 with whole numbers (-7 / 2 is -3, and -7 % 3 is -1, as in C); 7.0 / 2 is 3.5
with open(p) as f: f.read()read_file(p) (`strFileError), write_file, append_file, read_bytes`
sys.argv, sys.exit(1)args(), exit(1)
argparsea struct of the options, opts = parse_args[Options]("what it does")
os.path.join, os.listdir, os.walk, glob.globjoin_path, list_dir, walk_dir, glob("src/**/*.jo"); make_dirs, rename_file, copy_file, delete_file, file_time
subprocess.run(["ls", "-l"]), os.system("ls *.jo")run_program("ls", ["-l"]), run_shell("ls *.jo") (each gives its exit code and output; show = true: the output shows as it runs)
for line in open(p):if let f = open_file(p): then `read_line(f) -> str?FileError` (a file of any size)
hashlib.sha256(b).hexdigest()sha256(b) (bytes or text)
json.loads(s), json.dumps(x)parse_json(s) (a Json), from_json[Config](s) (into a struct), to_json(x)
requests.get(url), urllib.request.urlopen(url)import net, then r = net.fetch(url): r.status, r.text, and from_json[T](r.text) (fetching from the web)
requests.post(url, json=d, headers=h)net.fetch(url, method = "POST", body = to_json(d), headers = h)
urllib.parse.quote(s), urlencode(d), html.unescape(s)url_encode(s), url_query(d), html_unescape(s)
urljoin(base, link), urlsplit(url)url_join(base, link), parse_url(url) (u.host, u.port, u.path...)
s[:4], f"{s:.4}"first(s, 4) or "{s:.4}" (characters; s[..4] counts bytes, and can cut an é in two)
re.search(r"\d+", s)s.find(regex(r"\d+").unwrap()) (a Match?: m.text, m.groups)
Counter(ws), defaultdict(list)a map: a missing key starts at zero when changed (counts[w] += 1, groups[k].push(x)); reading one, m[k], is an error: m.get(k) ?? 0
set(), {1, 2}, x in sseen: Set[int] ({} where a Set is expected), {1, 2}, s.add(x), x in s; unique(xs) for an array without repeats
collections.deque, heapq.heappush(pq, (d, v))q: Deque[int] with q.push(x) and q.pop_front(); pq.heap_push((d, v)) and pq.heap_pop() on an array
bisect.bisect_left(xs, x), itertools.permutations(xs), combinations(xs, k)lower_bound(xs, x), permutations(xs), combinations(xs, k)
math.gcd, math.isqrt, pow(b, e, m)gcd(a, b), isqrt(n), pow_mod(b, e, m), inv_mod(a, m)
" ".join(map(str, xs)), print(x, file=sys.stderr)xs.join(" "), eprint(x)
None, if x is None:none, if x == none:; if let v = x: gets what is inside
match s: with case Rect(w, h) if w == h:, case n if n > 100:match s: with .rect(w, h) if w == h: (a variant of an enum, its fields by position), _ as n if n > 100:; if let .rect(w, h) = s: for one variant
t[0] (a tuple)t.0
global x before x = 1 or x += 1 in a functionglobal x before x = 1; x += 1, x.f = 1 and xs[i] = 1 change the global without it
max(xs, key=len), sorted(xs, key=..., reverse=True)max(xs, key = len), sorted(xs, key = (x): x.age, descending = true)
try: ... except: ...a function gives back what went wrong as a value (-> Config | JsonError), checked with if r is JsonError:, or passed on to the caller with ? (cfg = load(p)?)
def test_x(): assert ... (pytest)test "x": assert(...), run with sloppy test file.jo
sqlite3.connect(p), cur.execute(sql, (a, b)), fetchall()import sqlite, db = unwrap(sqlite.open(p)), db.run(sql, [a, b]), db.query[Todo](sql, [a]) (the rows into a struct's fields), db.value(sql) (keeping data)
Flask: @app.route("/todos", methods=["POST"]) above a functionimport http, then http.post("/todos", add_todo): a route is a call, given the function; http.serve(8080) (writing a server)
request.form["name"], request.form.getlist("tag"), request.fileshttp.form(r).get("name") ?? "", http.form_all(r, "tag"), http.uploads(r)
request.args.get("q"), request.get_json()r.query.get("q"), http.read_json(r, item) (into a struct; it gives the 400 to answer when the body does not fit)
jsonify(d), render_template("hi.html", name=n)http.json(d), http.html("<p>Hello {html_escape(n)}</p>") (what a user wrote, escaped)
redirect(url_for("home")), abort(404)return http.redirect("/", 303), return http.status(404) (http.json_error(404, "why") for an API)
session["user"] = u, flash("Saved")http.set_signed_cookie(res, "user", u, SECRET), read by http.signed_cookie(r, "user", SECRET); a message for the next page: a short cookie, or ?saved=1 on the redirect
app.test_client().post("/login", data=d)http.handle("POST", "/login", body, headers): the answer, with no server; or http.listen(0), http.port() and net.fetch(url, follow = false)
big integers: 2 ** 1000, int("123..."), math.factorial(100)int is 64 bits and wraps around (checked_mul(a, b) is none where it would); past that, BigInt keeps every digit: bigint(2) ^ 1000, bigint("123..."), f *= i from f = bigint(1), with + - * / %, comparisons, print and pow_mod, gcd, isqrt as for ints

For contests and Advent of Code (reading all the input at once, the containers, binary search, number theory): Contests and Advent of Code.

Coming from Go

Tasks are goroutines that take turns on one thread: spawn((): ...) starts one, and one that waits (a channel, a fetch, a connection, sleep) lets the others run. For the processor's cores, parallel_map shares out work, and the compiler checks its functions for data races.

GoSloppy
go run main.go, go buildsloppy main.jo, sloppy build main.jo (--release for faster code)
go f(x)t = spawn((): f(x)); t.wait() is its result (tasks and channels)
ch := make(chan int), make(chan int, 10)ch = channel[int](), channel[int](10)
ch <- v, v, ok := <-ch, close(ch)ch.send(v), if let v = ch.receive(): (none once closed and empty), ch.close()
for v := range chloop v in ch:
sync.WaitGroup, errgroupwait_all(tasks): their results, in order; or a group, g = task_group(), g.spawn((): ...), g.wait() (false if one panicked: the others are cancelled, g.why() says what)
a worker pool over fetches, errgroup with SetLimit(8)rs = net.fetch_all(urls, at_once = 8, retries = 2): the answers in order, each failed or busy one asked again
goroutines for CPU workparallel_map(xs, f), parallel_range(n, f) and parallel_update(xs, f) run f on every core and give back its results, in order
sync.Mutexnot needed: tasks take turns, and between two waits nothing else runs; parallel_map's function cannot change a variable it shares (the compiler says so: return values instead), and a count the threads share is an Atomic (done = atomic(0), done.add(1))
selectselect: with arms ch.receive() as v:, ch.send(x):, t.wait() as r: (a task has ended), stopping(): (ctrl-c), after 2.0: and else:; one channel alone: ch.receive(wait = 2.0), ch.send(x, wait = 2.0)
a nil channel in a select (ch = nil once it is closed)the channel in an optional, set to none: an arm on none is never ready (a: Channel[int]? = ch, then a = none)
runtime.Gosched()yield_now()
"all goroutines are asleep - deadlock!"the same: every task waiting on what none will do is told, with where each waits
context.WithTimeout, cancellingnet.fetch(url, wait = 5.0) (and fetch_start, fetch_all): status 0 and r.why when the time runs out; net.fetch_cancel(f) stops one
ctx.Done(), cancel()t.cancel(): the task's waits (sleep, a channel, select, the network's) end at once with nothing, and cancelled() is true in it, for it to clean up and end; a group's g.cancel() cancels every one
signal.NotifyContext(ctx, os.Interrupt), graceful shutdownloop not stopping(): ...: ctrl-c and SIGTERM make stopping() true (and end the sleep and net.wait of a task that has asked it); on_quit = (): ... runs as the program ends. A task that goes on after main has ended is told; a second ctrl-c ends the program
a goroutine dump (SIGQUIT)report_tasks(): what each task waits for, where, and where it was spawned; task_count()
if err != nil { return err }x = f()?: a failure (an error struct, or none) goes back to the caller as it is
errors.New, a type implementing errorerror struct LoadError: with the fields the caller needs; the function returns Config | LoadError, and the caller checks if r is LoadError:
func save() errorsave = () -> void | SaveError:; save()? passes the error on
defer f.Close()defer f.close(): runs as the block ends, by a return or a ? too
v, ok := m[k], m[k]++if let v = m.get(k):, m[k] += 1 (a missing key starts at zero)
append(xs, x), len(xs), xs[1:3]xs.push(x), xs.len(), xs[1..3)
structs and methodsstruct Box: and functions taking one: area = (b: Box) -> f64: b.w * b.h is called b.area()
fmt.Printf("%-10s %5.2f\n", s, x)print("{s:<10} {x:5.2f}")
flag.Bool("words", false, "count words")a struct of the options, opts = parse_args[Options]("what it does"), the comments as the help
encoding/json, struct tagsfrom_json[Item](s) (fields by name), to_json(x), parse_json(s) for any shape; a JSON name that is a keyword is a field with _ after it (when_ is "when")
bufio.Scanner over a fileif let f = open_file(p): then `read_line(f) -> str?FileError`
regexp.MustCompile(expr)regex(r"...").unwrap(), made once and used for every text
url.Parse, base.ResolveReference(ref)parse_url(s) (u.host, u.port, u.path), url_join(base, link)
http.HandleFunc, http.ListenAndServeimport http, http.get("/todos/:id", handler), http.serve(8080) (writing a server)
middleware, rs/cors, gziphandlerhttp.before(f) (may answer early) and http.after(f), http.cors(["https://example.com"]); gzip is on (http.gzip = false)
bcrypt.GenerateFromPassword, subtle.ConstantTimeComparecrypto.hash_password(pw) and crypto.check_password(pw, stored) (PBKDF2-SHA256), crypto.constant_time_equal(a, b)
gorilla/websocket, a goroutine per connectionhttp.websocket(r) in a route; p = net.accept(wait = 1.0), a task for each with net.receive([p], wait = 30.0); net.close(p, 4001, "the room is full")
httptest.NewServerthe server in the same program: http.listen(port, host = "127.0.0.1"), spawn((): http.serve(port), background = true), then net.fetch (as above)
go test, func TestX(t *testing.T)test "x": assert(...) blocks, run by sloppy test file.jo (sloppy test file.jo x: only those named so)
a small static binarysloppy build --release tool.jo: one static executable (no libc; hello world is about 150 KB)
GOOS=windows GOARCH=amd64 go buildsloppy build tool.jo --target windows (linux, linux-arm64, macos, wasm), from any system; Linux, ARM and macOS builds are all named tool unless -o says otherwise, so give each its own: --target macos -o tool-mac

Coming from curses or bubbletea

import term is the terminal as curses, tcell or bubbletea give it, with the loop the program's own: draw everything into the screen (term.clear(), term.put(...)), term.flush() (only what changed goes out), then wait for term.read_event(). Keys come as an Event whose name is as bubbletea's msg.String(): "ctrl+c", "up", "enter", "a".

curses / tcell / bubbleteaSloppy
curses.wrapper(main), initscr() with cbreak(), noecho(), keypad(True); tcell.NewScreen() with Init(); tea.NewProgram(m, tea.WithAltScreen())term.start(): raw keys, the terminal's own screen, the cursor hidden; put back as it was by term.stop() or however the program ends (a panic, ctrl-c, SIGTERM too)
stdscr.getmaxyx(), screen.Size(), tea.WindowSizeMsgw, h = term.size() (columns, rows); a resize is an event of kind .resize, the screen resized already
stdscr.addstr(y, x, s, attr), screen.SetContent(x, y, r, nil, style)term.put(x, y, s, fg = term.RED, style = term.BOLD): x first, and it gives the column after
stdscr.refresh(), screen.Show()term.flush(): only the cells changed, in one write
stdscr.clear(), screen.Clear()term.clear() (each frame: only what changed is written anyway)
stdscr.getch(), get_wch(), screen.PollEvent(), tea.KeyMsge = term.read_event(): e.key (.char, .up, .f5...), e.text, e.ctrl, e.alt, e.shift, e.name ("ctrl+up")
stdscr.timeout(100), nodelay(True), tea.Tickterm.read_event(wait = 0.1) (none: nothing came), or a task that ticks while main waits for keys
curses.mousemask(ALL_MOUSE_EVENTS), screen.EnableMouse(), tea.WithMouseCellMotion()term.start(mouse = true): .press, .release, .drag, .wheel_up... with e.button, e.x, e.y (mouse_moves = true: tea.WithMouseAllMotion())
screen.EnablePaste(), tea.KeyMsg with Pastea paste is one event of kind .paste, its text in e.text (on by itself)
init_pair(1, COLOR_RED, COLOR_BLACK), color_pair(1); tcell.ColorRed; lipgloss's Color("205"), Color("#ff8000")fg = term.RED, bg = term.BLACK on each call; term.color(205), term.color(hex(0xff8000))
A_BOLD | A_UNDERLINE, A_REVERSE, A_DIMterm.BOLD | term.UNDERLINE, term.REVERSE, term.DIM (ITALIC, STRIKE)
stdscr.border(), curses.textpad.rectangle, lipgloss's bordersterm.box(x, y, w, h, title = "...", lines = .rounded) (.single, .double, .heavy); term.hline, term.vline
curs_set(1) and move(y, x)term.set_cursor(x, y) (shown after each flush), term.hide_cursor()
wcwidth, runewidth.StringWidth, lipgloss.Widthterm.text_width(s); term.fit(s, 20) cuts to 20 columns with a …
KeyboardInterrupt in getch(); tea.Quit on "ctrl+c"ctrl-c asks the program to stop (stopping(), on_quit), ending it at its next read_event if it does not look; term.start(ctrl_c_key = true) to read it as "ctrl+c"
curses.endwin() before a shell command, then refresh()term.stop(), run_program(cmd, show = true), term.start()
tests with teatest, a tcell.SimulationScreenterm.set_size(40, 10), draw, then term.screen_text() or term.render(); term.decode(bytes) for input

Coming from pygame

A pygame program owns its main loop: it reads events, moves things, draws onto the screen Surface, flips it and waits for the clock. A Sloppy game has no loop of its own: update and draw are called each frame, and the frame is shown after draw by itself. sloppy new my_game arcade and sloppy new my_game platformer are whole games to start from (a title screen, a score kept between runs, a level written as text).

window("Dodge", 800, 600)
player = Rect(380, 520, 40, 40)
rocks: Rect[]

update = (dt: f64):
    global player
    if key_down(.left): player.x -= 300 * dt         # speeds are per second: times dt
    if key_down(.right): player.x += 300 * dt
    player = player.clamp(Rect(0, 0, 800, 600))
    if every(1, 0.5): rocks.push(Rect(random(0, 780), -20, 20, 20))
    loop mut r in rocks: r.y += 200 * dt
    rocks.retain((r): r.y < 600)

draw = ():
    clear(rgb(0.1, 0.1, 0.15))
    rect(player, hex(0x40a0ff))
    loop r in rocks: rect(r, GRAY)
pygameSloppy
pygame.init(), set_mode((w, h)), while running: with events, clock.tick(60), display.flip()window("Title", w, h), then update = (dt: f64): and draw = ():: no loop, no events, no flip
QUITon_quit = ():, which the game calls as the window closes
KEYDOWN, key.get_pressed()[K_LEFT]key_pressed(.space) (pressed this frame), key_down(.left) (held); K_RETURN is .enter, K_ESCAPE .escape, K_a .a
mouse.get_pos(), mouse.get_pressed(), mouse.set_visible(False)mouse_pos(), mouse_down(.left) (mouse_pressed: this frame), show_cursor(false)
display.set_caption(s)set_title(s)
image.load(p).convert_alpha()load_texture(embed("p.png"), false).unwrap() at the top of the file (false: sharp pixels, for pixel art)
screen.blit(img, (x, y))sprite(img, vec2(x, y)) in draw
blit(sheet, pos, area), subsurfacesheet = sprite_sheet(img, 16, 16) and draw_frame(sheet, i, center), or sprite_region(img, src, center, size)
transform.flip, scale, rotatedraw_frame(..., flip_x = true) (or a negative width in sprite's size), sprite's size argument, angle = (radians)
img.get_width(), set_alpha(128)img.width, the tint's alpha: sprite(img, pos, tint = rgba(1, 1, 1, 0.5))
a Surface((w, h)) drawn ontort = render_target(w, h); in draw, draw_to(rt), the drawing, draw_to_screen(), then draw_target(rt, pos)
screen.fill(c)clear(c) at the top of draw; colors are 0 to 1, rgb(1, 0.5, 0), or hex(0xff8000)
draw.rect(s, c, r), draw.rect(s, c, r, 2), draw.circle, draw.linerect(r, c), rect_outline(r, 2, c), circle(center, radius, c) (ring for an outline), line(a, b, width, c)
Rect.colliderect, collidepoint, centeroverlaps(a, b), contains(r, p), center(r)
r.right, r.bottom, move, inflate, clamp, union, collidelistright(r), bottom(r), r.move(v), r.grow(2) (each side out by 2), r.clamp(bounds), union(a, b), first_overlap(r, rects); a Rect's fields are x, y, w, h
sprite.Group, spritecollide(..., dokill=True)an array of structs, changed in a loop mut e in enemies:, then enemies.retain((e): not e.dead)
math.Vector2vec2, length(v), normalize(v), distance(a, b), rotate(v, a) (radians: rotate(v, 90deg))
mixer.Sound(p).play(), mixer.music.load(p)jump = load_wav(embed("jump.wav")).unwrap() at the top, play(jump); play_music(load_music(embed("song.ogg")).unwrap()), or play(snd, looping = true)
font.SysFont(None, 24).render(s) and a blittext(s, pos, 24, color) with the built-in font; set_font(load_font(embed("font.ttf")).unwrap()) for another
time.get_ticks(), time.set_timerelapsed() (seconds), if every(1, 2.0): in update (true once each 2 s)
random.randint(1, 6), random.choice(xs)random_int(1, 7) (the top is left out), random_item(xs)
open("level.txt").read()str_from_bytes(embed("level.txt")): built into the game, so it works in a web page too; read_file(path).unwrap() reads the disk (native builds)
a high score in a filesave_value("best", best) and best = load_value("best", 0) (or save_data / load_data for text): a file natively, the browser's storage on the web
a small Surface scaled upwindow("Title", 320, 180) and pixel_art(); full_resolution() in draw before the HUD keeps its text sharp
RESIZABLE, VIDEORESIZE, toggle_fullscreen()windows are resizable, and the game keeps its 2D units (visible_rect() is what shows); toggle_fullscreen()
joystick.Joystick(0)gamepad_down(.a), left_stick() (any pad, or the pad's number first)

Also not as in Python: round(5.7) is 6.0 (int(round(x)) for a whole number), and angles are in radians. xs.remove(x) takes out the first element equal to x, as in Python, and xs.remove_at(i) the one at index i (Python's del xs[i]). To look at a frame without playing, or press keys at given frames: Testing a game.

Coming from PICO-8

A cart's _init, _update60 and _draw are a Sloppy game's top level, a step run 60 times a second, and draw. window("Title", 128, 128) with pixel_art() gives PICO-8's screen: a 2D unit is a pixel, scaled up sharp by whole pixels; lines, circles and rects are whole pixels in exactly their colors, and text draws in a 3 x 5 font like PICO-8's. Colors are values, not numbers: the palette is an array, PAL[8] its red. sloppy new my_game pico is a whole game to start from, with the palette, sprites written as text and a fixed 60 Hz step.

window("Cart", 128, 128)
pixel_art()
PAL = [hex(0x000000), hex(0x1d2b53), hex(0x7e2553), hex(0x008751), hex(0xab5236), hex(0x5f574f), hex(0xc2c3c7), hex(0xfff1e8),
       hex(0xff004d), hex(0xffa300), hex(0xffec27), hex(0x00e436), hex(0x29adff), hex(0x83769c), hex(0xff77a8), hex(0xffccaa)]
x = 64.0

tick = (dt: f64):                       # _update60
    global x
    if key_down(.left): x -= 1
    if key_down(.right): x += 1

update = (dt: f64): fixed_update(dt, tick)

draw = ():                              # _draw
    clear(PAL[1])                       # cls(1)
    circle(vec2(x, 64), 8, PAL[8])      # circfill(x, 64, 8, 8)
    text("HELLO", vec2(2, 2), 6, PAL[7])   # print("hello", 2, 2, 7)
PICO-8Sloppy
_init(), _update60() (_update), _draw()the top of the file runs once; update = (dt: f64): fixed_update(dt, tick) runs tick 60 times a second (rate = 30 for _update); draw = (): each frame
colors 0 to 15PAL[n] of an array of the 16 (hex(0xff004d) is red); sloppy new my_game pico has them
cls(c)clear(PAL[c])
pset(x, y, c), pget(x, y)rect(x, y, 1, 1, PAL[c]); the screen is not read back: keep what you need in variables, or an Image (img.get(x, y))
rectfill(x0, y0, x1, y1, c), rect(...)rect(x0, y0, x1 - x0 + 1, y1 - y0 + 1, PAL[c]) (a size, not the far corner), rect_outline(x, y, w, h, 1, PAL[c])
circfill(x, y, r, c), circ, line(x0, y0, x1, y1, c)circle(vec2(x, y), r, PAL[c]), ring(vec2(x, y), r, 1, PAL[c]), line(vec2(x0, y0), vec2(x1, y1), 1, PAL[c]): under pixel_art() whole pixels, a 1 wide line Bresenham's as PICO-8's; ellipse, arc, polyline too
spr(n, x, y, 1, 1, flip_x), ssprgfx = sprite_sheet(load_texture(embed("sheet.png")).unwrap(), 8, 8) at the top, then draw_frame(gfx, n, vec2(x, y), origin = vec2(0, 0), flip_x = true) (origin: its top left at the point; without, its middle); sprite_region for sspr
the sprite editora PNG from any editor (Aseprite: load_aseprite), or a sprite written in the code: texture(pixel_image("...77...\n..7cc7..", PAL)), a character a pixel, its color's number, . clear
map(...), mget(x, y), msetlevel = tilemap(tileset(load_texture(embed("sheet.png")).unwrap(), 8, 8), [tile_layer("ground", ROWS, "#=")]), draw_tilemap(level), tile_at(level, 0, x, y), set_tile(level, 0, x, y, id); tiles count from 1 (0 is none): tile n is sprite n - 1; load_tiled reads a Tiled map
pal(c0, c1), pal(), pal(c0, c1, 1)palette_swap(PAL[c0], PAL[c1]), palette_reset(), palette_swap(PAL[c0], PAL[c1], screen = true)
palt(c, true)a PNG's transparent pixels, or . in pixel_image
print(s, x, y, c)text(s, vec2(x, y), 6, PAL[c]): under pixel_art() in pixel_font(), 3 x 5 like PICO-8's (size 12 is twice as big); text_width(s, 6) is 4 a character
btn(⬅️), btnp(❎)key_down(.left) (or input_axis(): arrows, WASD and a pad's stick), key_pressed(.x) (just pressed); btnp's repeat while held: key_repeat(.down)
a gamepad, btn(i, p)gamepad_down(.a), gamepad_pressed, gamepad_repeat; gamepad_down(p, .a) for player p; action("fire", [.key(.x), .button(.a)]) and action_pressed("fire") (action_repeat) for keys the player can change
sfx(n), music(n)play(snd) of a sound made at the top: tone(440.0, 0.1, .square), sfx_coin(), sfx_explosion()..., load_wav(embed("hit.wav")).unwrap(); music: melody_loop("C5 E5 G5 E5", 150.0, .square) played with play(song, looping = true), mix([...]) for channels
rnd(10), flr(x), ceil, mid(lo, x, hi), abs, sgnrandom(0.0, 10.0) (random_int(0, 10): 0 to 9), floor(x) (int(x) for an int), ceil, clamp(x, lo, hi), abs, sign
sin(t), cos(t), atan2(dx, dy) (turns, y up)radians, y down: PICO-8's sin(t) is -sin(t * TAU), cos(t) is cos(t * TAU); atan2(dy, dx)
t(), time()elapsed() (seconds); frame_number()
cartdata("id"), dset(0, v), dget(0)save_value("best", best) and best = load_value("best", 0): by name, no cartdata (a file natively, the browser's storage on the web)
camera(x, y)translate(-x, -y) at the top of draw, or camera2d(vec2(x + 64, y + 64)) (it centers on its point)
clip(x, y, w, h)clip(vec2(x, y), vec2(w, h)), no_clip()
fillp(...)no fill patterns: a small texture repeated with sprite_tiled
tables: add(t, v), del(t, v), foreach, #tarrays: xs.push(v), xs.remove(v), loop x in xs:, xs.len(); an object is a struct
#include other.luause 'other.jo'
numbers are 16.16 fixed pointint (64 bits) and f64; positions are vec2 (of f32)
printh(s), stat(7)print(s) (to the terminal), fps()
Ctrl+R to run againsloppy watch cart.jo: each save reloads the code into the running game, which goes on where it was

Coming from pandas and matplotlib

pandas / NumPy / matplotlibSloppy
pd.read_csv("sales.csv")sales = from_csv[Sale](read_file("sales.csv").unwrap()): a struct per row, its fields by the header's names (or csv_rows(text): rows of text)
df["price"], df[df.price > 10][loop s in sales: s.price], sales.filter((s): s.price > 10.0); a soa Sale[] keeps each field as an array: t.price, t[t.price .> 10.0]
df.groupby("region").price.mean()group_by(sales, (s): s.region), then mean(...) of each group's prices; or a map: totals[s.region] += s.price
.dropna(), .fillna(0), ~maskxs[not is_nan.(xs)], x ?? 0.0 for an optional, not mask
np.mean, np.median, np.std, np.percentilemean, median, std_dev, percentile(xs, 90.0), histogram, correlation, cumsum
np.linalg.solve(A, b), A @ Bsolve(A, b), A * B (on f64[,] matrices)
plt.plot(...), plt.savefig("c.png")img = render_image(800, 500, (): ...lines, rects, text...), then save_png("c.png", img) (no window needed)
df.to_csv(...), json.dump(...)to_csv(rows), to_json(value)

Coming from Unity or Godot

ThereHere
a GameObject with components, a scene treea struct for each kind of thing, kept in arrays; update and draw go through them
a prefaba function that makes the struct (spawn_enemy(pos) -> Enemy)
methods, thisfunctions taking the thing first: e.hit(5) calls hit(e, 5); mut lets one change it
inheritancea struct holding another (base: Body), or a union of kinds (type Enemy = Walker | Flyer) with match
coroutines, yielda timer in a field, counted down each frame (e.wait -= dt)
OnTriggerEnter, eventslook each frame (w.contacts(), a distance check) and act
Time.timeScale, pausingthe game's own clock: add dt only while not paused
the Animatoranim: Animator, anim.play(hero, "Walk", fade = 0.2), anim.update(hero, dt) and draw_model(hero, pose = anim.pose(hero)); pose_at and blend_poses for manual control
the inspectorprint(x) shows any value, and sloppy watch reloads the code as it changes
Time.deltaTimedt, what update = (dt: f64): is given
AudioSettings.dspTime, AudioServer.get_time_since_last_mix()audio_time(): the audio clock, smooth, the sound heard so far (see rhythm games)
AudioSource.PlayScheduled(t), PlayDelayed(d)play(s, at = t) on the audio clock, play(s, delay = d), to the sample (play_music too)
AudioSource.time, Pause(), UnPause(), seekingvoice_time(id), pause(id), resume(id), seek(id, t)
AudioServer.get_output_latency()audio_latency()
Input.GetKey(KeyCode.W), GetKeyDown, GetAxiskey_down(.w), key_pressed(.space), input_axis()
Mathf.Clamp, Mathf.Sin, Debug.Logplain functions: clamp, sin, lerp, PI; print
Instantiate, Destroya function that makes the struct, pushed onto its array; xs.remove_at(i) or xs.retain(...)
List<T>, Dictionary<K, V>, nullT[], {K: V}, none (a T? may be none: if let v = x:)
Rigidbody, Physics.Raycast, a CharacterControllerimport physics3d: w.add_sphere(...), w.raycast(a, b), w.character(...) and w.walk(...)
Quaternion.Euler(0, 45, 0), LookRotationquat_euler(0, 45deg, 0), facing(dir); or matrices: rotation_y(45deg) (angles are radians: 45deg is 45 degrees)
q1 * q2, q * vquat_mul(q1, q2), quat_rotate(q, v) (quaternions are vec4s: * multiplies their parts one by one)
transform.forwarda model's front is +z (glTF's), turned as it is: transform_dir(m, vec3(0, 0, 1)); a camera looks along -z
Cinemachine, a third-person cameracam = follow_camera(), then update(cam, player_pos, dt) and camera3d(cam); walk along flat_forward(cam)

Where next