Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ <h1>Pytml Demos</h1>
<article class="card"><h2>Greeting</h2><p>Use browser input and Python to build a tiny interactive page.</p><a class="open" href="examples/greeting.html">Open demo →</a></article>
<article class="card"><h2>Joystick</h2><p>Pointer/touch joystick controls exposed to Python.</p><a class="open" href="examples/joystick.html">Open demo →</a></article>
<article class="card"><h2>Packages</h2><p>Install Python packages through micropip and use them in the browser.</p><a class="open" href="examples/packages.html">Open demo →</a></article>
<article class="card"><h2>Game Starter</h2><p>Move a player with keyboard, gamepad or on-screen D-pad using one set of controls.</p><a class="open" href="examples/game-starter.html">Open demo →</a></article>
<article class="card"><h2>Space Shooter</h2><p>A complete tiny game: game loop, sound effects, touch controls, pause and saved high scores.</p><a class="open" href="examples/game-space-shooter.html">Open demo →</a></article>
<article class="card"><h2>Gamepad Tester</h2><p>Live buttons, sticks and rumble for any connected controller.</p><a class="open" href="examples/game-gamepad.html">Open demo →</a></article>
<article class="card"><h2>Sound Lab</h2><p>Built-in retro sound effects and a tone generator. No audio files needed.</p><a class="open" href="examples/game-sound.html">Open demo →</a></article>
<article class="card"><h2>Sprite Animation</h2><p>Sprite sheets, animation and crisp pixel-art rendering on a canvas.</p><a class="open" href="examples/game-sprites.html">Open demo →</a></article>
</div>
</main>
</body>
Expand Down
1,916 changes: 1,910 additions & 6 deletions dist/pytml.js

Large diffs are not rendered by default.

2,088 changes: 1,825 additions & 263 deletions dist/pytml.min.js

Large diffs are not rendered by default.

156 changes: 156 additions & 0 deletions docs/GAME_KIT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# Pytml Game Kit

New in Pytml 2.6. Import what you need from `pytml`; the kit is compiled the first time you use any of it, so pages that don't use it pay nothing.

```python
from pytml import Canvas, loop, controls, sfx
```

## Game loop

```python
@loop # or: lp = loop(update, render=draw, fixed=1/60, fps=60)
def update(dt): # dt = seconds since the last frame (clamped to max_dt=0.1)
...
```

`loop(update, render=None, fixed=None, fps=None, max_dt=0.1)` returns a `Loop`.

- `update` may take `dt` or no arguments, and may be `async`.
- `fixed=1/60` calls `update(1/60)` as many times as needed per frame (at most 8) and calls `render()` once. `loop.alpha` is the leftover fraction, for interpolation.
- `fps=30` caps the update rate.
- Methods: `start()`, `stop()`, `pause()`, `resume()`, `toggle_pause()`. Info: `running`, `paused`, `time`, `frame`, `fps`.
- A paused loop does not poll input, so unpause from a button or your own DOM event, or keep a `paused` flag inside `update` as the Space Shooter demo does.
- If `update` raises, the loop stops and the traceback is shown on the page.

## Keyboard: `keys`

Keys are physical positions (`KeyboardEvent.code`), so WASD works on every layout.

| Call | Meaning |
| --- | --- |
| `keys.down("a", "left")` | any of these keys is held |
| `keys.pressed("space")` | went down this frame |
| `keys.released("space")` | went up this frame |
| `keys.axis("left", "right")` | -1, 0 or 1 |

Names: single letters and digits, `left right up down space enter escape tab shift ctrl alt backspace`, or any exact code such as `KeyW` or `Numpad1`. Arrows and Space do not scroll the page while you play (not inside text fields). Turn that off with `keys.prevent_scroll = False`. Held keys are released when the window loses focus.

## Gamepad

```python
pad = gamepad(0)
pad.connected, pad.id
pad.down("a"), pad.pressed("a"), pad.released("a"), pad.button("rt") # button() is analog 0..1
pad.axis("lx"), pad.left_stick, pad.right_stick # dead zone removed
pad.rumble(300, strong=1.0, weak=0.5) # Chrome / Edge
```

Buttons: `a b x y lb rb lt rt back start ls rs up down left right home` (aliases `cross circle square triangle l1 r1 l2 r2 select options`). Set `pad.deadzone` (default 0.15). `pressed`/`released` need a running `loop`. `connected_gamepads()`, `on_gamepad_connected(cb)` and `on_gamepad_disconnected(cb)` are available; browsers only report a pad after its first button press.

## One set of controls: `controls`

```python
controls.use_defaults() # left/right/up/down, action, cancel, pause
controls.bind("jump", "space", "up", "pad:a", "touch:jump_btn")
controls.bind("left", "left", "a", "pad:left", "pad:lx-", "touch:dpad.left", "stick:move.left")

controls.down("jump"); controls.pressed("jump"); controls.released("jump")
controls.axis("left", "right") # -1..1, analog aware
controls.vector() # Vec2, diagonals are not faster
controls.value("left") # 0..1
```

| Source | Meaning |
| --- | --- |
| `"space"`, `"a"`, `"ArrowLeft"` | keyboard |
| `"pad:a"`, `"pad:left"` | gamepad button on any connected pad |
| `"pad:lx-"`, `"pad:ry+"` | stick direction (`lx ly rx ry`) |
| `"touch:id"` | a `touch_button("id")` |
| `"touch:id.left"` | a `dpad("id")` direction |
| `"stick:id.left"` | a `joystick("id")` direction |

An action counts as down at 0.5 strength (`controls.threshold`). `pressed` and `released` need a running `loop`.

## On-screen controls

```python
dpad("dpad") # <div id="dpad"></div>, builds four arrows (8-way)
touch_button("fire", "FIRE") # <div id="fire"></div>
```

Both expose live state (`d.left`, `d.x`, `b.down`). The default look uses zero-specificity CSS (`:where(...)`), so any CSS you write wins. To show them only on phones: `@media (pointer: coarse) { .touch { display: flex } }`.

## Canvas

```python
screen = Canvas("screen", 480, 320, pixelated=False, fit=False, hidpi=True)
screen.clear("#111") # or clear() to make it transparent
screen.rect(x, y, w, h, color, fill=True, line_width=1)
screen.circle(x, y, r, color) screen.line(x1, y1, x2, y2, color, width)
screen.polygon([(0, 0), (10, 0), (5, 9)], color)
screen.text("Hi", x, y, color="#fff", size=16, align="left", baseline="top", bold=False)
screen.draw_image(img, x, y, w=None, h=None, src=(sx, sy, sw, sh), flip_x=False, rotation=0, alpha=1)
screen.save(); screen.translate(x, y); screen.rotate(rad); screen.scale(s); screen.restore()
screen.mouse_x, screen.mouse_y, screen.mouse_down # in logical coordinates, even when scaled
screen.ctx # raw CanvasRenderingContext2D
```

Colors are CSS strings or tuples `(r, g, b)` / `(r, g, b, a)`. `pixelated=True` gives crisp pixel art. `fit=True` scales the canvas down to fit its container while keeping the aspect ratio. `Canvas.create(w, h)` makes an off-screen canvas you can draw on and use as a sprite source.

## Images and sprites

```python
hero = await load_image("hero.png")
assets = await load_images({"hero": "hero.png", "tiles": "tiles.png"})
sheet = SpriteSheet(hero, 16, 16) # frame size, optional margin= and spacing=
walk = Animation(sheet, [0, 1, 2, 3], fps=8) # loop=False to play once
walk.update(dt); walk.draw(screen, x, y, 64, 64, flip_x=True)
sheet.draw(screen, 5, x, y) # draw frame 5
```

Images can come from any URL the page can load, including relative paths on `file://` pages. Pass `cors=True` only if you need to read pixels back; it requires the server to send CORS headers.

## Sound

```python
sfx.play("coin") # coin jump blip laser hit explosion powerup error lose win
beep(880, 120, "square", volume=0.25, slide=-300)
jump = await load_sound("jump.wav"); jump.play(volume=1, rate=1.0, pan=0) # overlapping plays are fine
song = music("theme.mp3", loop=True, volume=0.6); song.play()
audio.volume = 0.5; audio.muted = True
```

Browsers keep audio silent until the first click, tap or key press; Pytml resumes it on that first gesture. `load_sound` uses Web Audio and falls back to `<audio>` if `fetch` is not possible (for example on `file://`).

## Math and collisions

`Vec2(x, y)` supports `+ - * /`, `length`, `normalized()`, `dot`, `rotate`, `lerp`, `distance_to`, `clamp_length`, `Vec2.from_angle`.
`Rect(x, y, w, h)` has `right bottom centerx centery center`, `overlaps(other)`, `contains(px, py)`, `move(dx, dy)`, `inflate`, `copy`.
Functions: `rect_overlap`, `circle_overlap`, `clamp`, `lerp`, `sign`, `distance`, `approach`.

## Saving

```python
save_game("slot1", {"level": 3}) # any JSON-friendly value, stored in localStorage
load_game("slot1", default={})
delete_game("slot1")

scores = HighScores("my-game", limit=10) # lower_is_better=True for race times
rank = scores.submit(1200, "AR") # 1 = new best, None = did not make the table
scores.best; scores.top(5)
```

Saves are per browser and per site.

## Fullscreen and vibration

```python
await fullscreen() # call from a click or key handler
await exit_fullscreen()
vibrate(80); vibrate([100, 50, 100])
```

## Publishing

A Pytml game is one static HTML file, so any static host works (GitHub Pages, Netlify, Vercel and similar).
76 changes: 76 additions & 0 deletions examples/game-gamepad.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pytml Gamepad Tester</title>
<script src="https://pytml.vercel.app/pytml.js"></script>
<style>
body { margin: 0; padding: 20px; background: #0d1117; color: #c9d1d9; font-family: system-ui, sans-serif; text-align: center; }
#screen { display: block; margin: 16px auto; border: 2px solid #30363d; border-radius: 8px; background: #111827; }
button { font: inherit; padding: 8px 16px; border-radius: 8px; border: 1px solid #30363d; background: #21262d; color: #c9d1d9; cursor: pointer; }
#info { opacity: .8; min-height: 1.4em; }
</style>
</head>
<body>
<h1>Gamepad Tester</h1>
<div id="info">Connect a controller and press any button.</div>
<canvas id="screen"></canvas>
<button id="rumble">Rumble</button>

<py1>
from pytml import Canvas, loop, gamepad, connected_gamepads, on_gamepad_connected, on_gamepad_disconnected

screen = Canvas("screen", 520, 300, fit=True)
BUTTONS = ["a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "ls", "rs", "up", "down", "left", "right", "home"]
last = {"name": None}


def say(pad, state):
info.text = f"{state}: {pad.id}"


on_gamepad_connected(lambda pad: say(pad, "Connected"))
on_gamepad_disconnected(lambda pad: say(pad, "Disconnected"))


def buzz(event):
pads = connected_gamepads()
if pads and not pads[0].rumble(300):
info.text = "This browser/controller does not support rumble."


rumble.on("click", buzz)


def stick(cx, cy, vec, label):
screen.circle(cx, cy, 46, "#30363d", fill=False, line_width=2)
screen.circle(cx + vec[0] * 34, cy + vec[1] * 34, 11, "#4aa8ff")
screen.text(f"{vec[0]:+.2f}, {vec[1]:+.2f}", cx, cy + 58, "#8b949e", 12, align="center")
screen.text(label, cx, cy - 72, "#c9d1d9", 13, align="center")


@loop
def draw(dt):
screen.clear("#111827")
pads = connected_gamepads()
if not pads:
screen.text("No controller detected", 260, 150, "#8b949e", 18, align="center", baseline="middle")
return
pad = pads[0]
for i, name in enumerate(BUTTONS):
col, row = i % 9, i // 9
x, y = 40 + col * 56, 24 + row * 44
v = pad.button(name)
screen.rect(x, y, 48, 32, (74 + int(v * 100), 168, 255, 0.15 + v * 0.85))
screen.text(name, x + 24, y + 16, "#fff", 12, align="center", baseline="middle")
if pad.pressed(name):
last["name"] = name
stick(150, 200, pad.left_stick, "Left stick")
stick(370, 200, pad.right_stick, "Right stick")
screen.text(f"Last pressed: {last['name'] or '-'}", 260, 280, "#8b949e", 13, align="center")
</py1>

<p><a href="../demo.html">← Back to demos</a></p>
</body>
</html>
72 changes: 72 additions & 0 deletions examples/game-sound.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pytml Sound Lab</title>
<script src="https://pytml.vercel.app/pytml.js"></script>
<style>
body { font-family: system-ui, sans-serif; max-width: 560px; margin: 30px auto; padding: 0 16px; }
.row { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
button { font: inherit; padding: 10px 16px; border-radius: 8px; border: 1px solid #ccc; background: #f6f8fa; cursor: pointer; }
button:active { background: #e5e7eb; }
label { display: block; margin: 12px 0 4px; }
input[type=range] { width: 100%; }
code { background: #f4f4f5; padding: 2px 6px; border-radius: 4px; }
</style>
</head>
<body>
<h1>Sound Lab</h1>
<p>Retro sound effects built into Pytml. No audio files needed.</p>

<div class="row">
<button id="b_coin">coin</button><button id="b_jump">jump</button><button id="b_blip">blip</button>
<button id="b_laser">laser</button><button id="b_hit">hit</button><button id="b_explosion">explosion</button>
<button id="b_powerup">powerup</button><button id="b_error">error</button>
<button id="b_lose">lose</button><button id="b_win">win</button>
</div>

<h3>Make your own</h3>
<label>Pitch: <span id="pitch_v">440</span> Hz</label>
<input id="pitch" type="range" min="80" max="1600" value="440">
<label>Slide: <span id="slide_v">0</span> Hz</label>
<input id="slide" type="range" min="-800" max="800" value="0">
<label>Length: <span id="dur_v">150</span> ms</label>
<input id="dur" type="range" min="30" max="800" value="150">
<label>Wave
<select id="wave"><option>square</option><option>sawtooth</option><option>triangle</option><option>sine</option></select>
</label>
<div class="row"><button id="play">Play tone</button></div>
<label>Master volume</label>
<input id="vol" type="range" min="0" max="100" value="100">
<pre id="code"></pre>

<py1>
from pytml import sfx, beep, audio

for name in sfx.names:
elements[f"b_{name}"].on("click", lambda e, n=name: sfx.play(n))


def show(event=None):
pitch_v.text, slide_v.text, dur_v.text = pitch.value, slide.value, dur.value
code.text = f"beep({pitch.value}, {dur.value}, '{wave.value}', slide={slide.value})"


def tone(event):
show()
beep(int(pitch.value), int(dur.value), wave.value, slide=int(slide.value))


pitch.on("input", show)
slide.on("input", show)
dur.on("input", show)
wave.on("change", show)
play.on("click", tone)
vol.on("input", lambda e: setattr(audio, "volume", int(vol.value) / 100))
show()
</py1>

<p><a href="../demo.html">← Back to demos</a></p>
</body>
</html>
Loading
Loading