diff --git a/11a7f54ede6ebe4f809bce13cc034aef.txt b/11a7f54ede6ebe4f809bce13cc034aef.txt new file mode 100644 index 0000000..7f1e324 --- /dev/null +++ b/11a7f54ede6ebe4f809bce13cc034aef.txt @@ -0,0 +1 @@ +11a7f54ede6ebe4f809bce13cc034aef diff --git a/CHANGELOG.md b/CHANGELOG.md index 20d9105..3c17ea6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,19 @@ -# Pytml 2.5.1 +# Pytml 2.6.0 -- Supports inline Python on `file://` pages while keeping Pyodide on HTTPS. -- Loads Pyodide only when a page contains Python blocks. -- Gives a clear error for relative local Python `src` files under `file://`. -- Improves async callbacks, timer handling, and HTML escaping. +- Keeps Pyodide `314.0.7` as the runtime. +- Injects the `pytml` helper module at startup. +- Embeds `pytml.game` (Game Kit) and compiles it lazily on first use. +- Updates multilingual READMEs and the main website copy for the 2.6 release. Changelog +## 2.6.0 — 2026-11-29 + +- Kept Pyodide `314.0.7` as the runtime in Pytml 2.6. +- Injected the `pytml` helper module during startup. +- Embedded the Game Kit as `pytml.game` with lazy first-use compilation. +- Updated README files (EN/DE/JA/ZH) and website metadata/content to reflect 2.6. + ## 2.5.1 — 2026-10-19 - Added inline Python support for `file://` pages and clearer errors for local Python `src` files. diff --git a/LICENSE b/LICENSE index ac79daf..4e40991 100644 --- a/LICENSE +++ b/LICENSE @@ -173,29 +173,5 @@ incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. Copyright 2026 Aswanth R(NodeX-AR) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/README.md b/README.md index cf05d0c..c7155ab 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,8 @@ **Run Python in your browser with zero configuration — no server, just a script tag.** -Pytml 2.5 is a lightweight JavaScript bridge built on **Pyodide 314.0.7**. Write Python inside HTML, interact with ordinary DOM elements, and use the small numbered UI syntax supported by the 2.5 runtime. +Pytml 2.6 is a lightweight JavaScript bridge built on **Pyodide 314.0.7**. Write Python inside HTML, interact with ordinary DOM elements, and use the small numbered UI syntax supported by the 2.6 runtime. +Pytml 2.6 also injects the `pytml` helper module at startup, and embeds the Game Kit (`pytml.game`) so it compiles lazily on first use. > **Official Pyodide Related Project. Thank you to the Pyodide team for the support!** > **Featured in [Python Weekly Issue 772](https://www.pythonweekly.com/p/python-weekly-issue-772-november-19-2026)!** @@ -37,9 +38,9 @@ print(f"Hi {name}!") ``` -## Pytml 2.5 UI Syntax +## Pytml 2.6 UI Syntax -Inside a `` block, Pytml 2.5 recognizes numbered UI tags such as: +Inside a `` block, Pytml 2.6 recognizes numbered UI tags such as: ```html diff --git a/README_de.md b/README_de.md index 0d32f55..03fad9b 100644 --- a/README_de.md +++ b/README_de.md @@ -15,7 +15,8 @@ **Python im Browser ausführen – ohne Konfiguration, ohne Server, nur ein Script-Tag.** -Pytml 2.5 ist eine leichtgewichtige JavaScript-Brücke auf Basis von **Pyodide 314.0.7**. Schreiben Sie Python direkt in HTML, arbeiten Sie mit gewöhnlichen DOM-Elementen und nutzen Sie die kleine nummerierte UI-Syntax, die die 2.5-Laufzeitumgebung unterstützt. +Pytml 2.6 ist eine leichtgewichtige JavaScript-Brücke auf Basis von **Pyodide 314.0.7**. Schreiben Sie Python direkt in HTML, arbeiten Sie mit gewöhnlichen DOM-Elementen und nutzen Sie die kleine nummerierte UI-Syntax, die die 2.6-Laufzeitumgebung unterstützt. +Pytml 2.6 injiziert beim Start außerdem automatisch das Hilfsmodul `pytml`; das Game Kit (`pytml.game`) ist eingebettet und wird bei der ersten Nutzung lazy kompiliert. > **Offizielles Pyodide-Related-Project. Vielen Dank an das Pyodide-Team für die Unterstützung!** > **Vorgestellt in [Python Weekly Ausgabe 772](https://www.pythonweekly.com/p/python-weekly-issue-772-november-19-2026)!** @@ -42,9 +43,9 @@ print(f"Hi {name}!") Der Inhalt des ``-Tags wird als Python-Code ausgeführt. Die Ausgabe von `print()` wird auf der Seite angezeigt, und `input()` funktioniert als Eingabe im Browser. -## Pytml-2.5-UI-Syntax +## Pytml-2.6-UI-Syntax -Innerhalb eines ``-Blocks (z. B. ``, ``) erkennt Pytml 2.5 nummerierte UI-Tags wie diese: +Innerhalb eines ``-Blocks (z. B. ``, ``) erkennt Pytml 2.6 nummerierte UI-Tags wie diese: ```html diff --git a/README_ja.md b/README_ja.md index a64873b..4d7b9d5 100644 --- a/README_ja.md +++ b/README_ja.md @@ -14,7 +14,8 @@ **設定不要でブラウザ上でPythonを実行 ― サーバーは不要、scriptタグ1行だけです。** -Pytml 2.5は、**Pyodide 314.0.7** をベースにした軽量なJavaScriptブリッジです。HTMLの中にPythonを書き、通常のDOM要素を操作でき、2.5ランタイムが対応する番号付きの簡易UI構文も使えます。 +Pytml 2.6は、**Pyodide 314.0.7** をベースにした軽量なJavaScriptブリッジです。HTMLの中にPythonを書き、通常のDOM要素を操作でき、2.6ランタイムが対応する番号付きの簡易UI構文も使えます。 +Pytml 2.6では起動時に `pytml` ヘルパーモジュールが自動注入され、Game Kit(`pytml.game`)は埋め込み済みで初回利用時に遅延コンパイルされます。 > **Pyodide公式の関連プロジェクトです。サポートしてくださったPyodideチームに感謝します。** > **Ditampilake ing [Python Weekly Edisi 772](https://www.pythonweekly.com/p/python-weekly-issue-772-november-19-2026)!** @@ -41,9 +42,9 @@ print(f"Hi {name}!") `` タグの中がPythonコードとして実行されます。`print()` の出力は画面に表示され、`input()` はブラウザ上の入力として動作します。 -## Pytml 2.5 のUI構文 +## Pytml 2.6 のUI構文 -`` ブロック(``、`` など)の中では、Pytml 2.5は次のような番号付きUIタグを認識します。 +`` ブロック(``、`` など)の中では、Pytml 2.6は次のような番号付きUIタグを認識します。 ```html diff --git a/README_zh.md b/README_zh.md index 4d0bcd7..b6b2496 100644 --- a/README_zh.md +++ b/README_zh.md @@ -14,7 +14,8 @@ **零配置,在浏览器中运行 Python——无需服务器,只需一个 script 标签。** -Pytml 2.5 是一个基于 **Pyodide 314.0.7** 的轻量级 JavaScript 桥接库。你可以直接在 HTML 中编写 Python,操作普通的 DOM 元素,并使用 2.5 运行时支持的简易编号式 UI 语法。 +Pytml 2.6 是一个基于 **Pyodide 314.0.7** 的轻量级 JavaScript 桥接库。你可以直接在 HTML 中编写 Python,操作普通的 DOM 元素,并使用 2.6 运行时支持的简易编号式 UI 语法。 +在 Pytml 2.6 中,启动时会自动注入 `pytml` 辅助模块,Game Kit(`pytml.game`)已内置并在首次使用时延迟编译。 > **Pyodide 官方相关项目。感谢 Pyodide 团队的支持!** > **收录于 [Python 周刊第 772 期](https://www.pythonweekly.com/p/python-weekly-issue-772-november-19-2026)!** @@ -40,9 +41,9 @@ print(f"Hi {name}!") `` 标签中的内容会作为 Python 代码运行。`print()` 的输出会显示在页面上,`input()` 则以浏览器输入的方式工作。 -## Pytml 2.5 UI 语法 +## Pytml 2.6 UI 语法 -在 `` 块(如 ``、``)内,Pytml 2.5 能识别如下带编号的 UI 标签: +在 `` 块(如 ``、``)内,Pytml 2.6 能识别如下带编号的 UI 标签: ```html diff --git a/demo.html b/demo.html index 574ab06..9551532 100644 --- a/demo.html +++ b/demo.html @@ -29,6 +29,11 @@

Pytml Demos

Greeting

Use browser input and Python to build a tiny interactive page.

Open demo →

Joystick

Pointer/touch joystick controls exposed to Python.

Open demo →

Packages

Install Python packages through micropip and use them in the browser.

Open demo →
+

Game Starter

Move a player with keyboard, gamepad or on-screen D-pad using one set of controls.

Open demo →
+

Space Shooter

A complete tiny game: game loop, sound effects, touch controls, pause and saved high scores.

Open demo →
+

Gamepad Tester

Live buttons, sticks and rumble for any connected controller.

Open demo →
+

Sound Lab

Built-in retro sound effects and a tone generator. No audio files needed.

Open demo →
+

Sprite Animation

Sprite sheets, animation and crisp pixel-art rendering on a canvas.

Open demo →
diff --git a/dist/pytml.js b/dist/pytml.js index 035bd10..7d0d5df 100644 --- a/dist/pytml.js +++ b/dist/pytml.js @@ -1,14 +1,17 @@ /* - * Pytml 2.5.1 + * Pytml 2.6.0 * Python + HTML, powered by Pyodide. * - * Pytml 2.5 includes a lightweight inline UI preprocessor for blocks. + * Pytml 2.6 adds a persistent Pyodide cache (Cache Storage API) and the + * Pytml Game Kit (game loop, keyboard/gamepad/touch input, canvas, sprites, + * sound, collisions, save games). The Game Kit is loaded lazily, so pages + * that do not use it pay nothing. * The full document/language compiler remains planned for v3.0. */ (function (global) { 'use strict'; - const VERSION = '2.5.1'; + const VERSION = '2.6.0'; const PYODIDE_VERSION = '314.0.7'; const PYODIDE_INDEX = `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`; const PYODIDE_SCRIPT = `${PYODIDE_INDEX}pyodide.js`; @@ -16,6 +19,186 @@ const IS_FILE_PROTOCOL = typeof location !== 'undefined' && location.protocol === 'file:'; const PY_BLOCK = /^py(?:\d+)?$/i; + + // --- Configuration ------------------------------------------------------- + // Read from window.PytmlConfig (set before the script tag) and from data-* + // attributes on the + const SCRIPT_TAG = (typeof document !== 'undefined' && document.currentScript) || null; + const FALSE_WORDS = ['off', 'false', '0', 'no', 'none']; + + function readConfig() { + const cfg = Object.assign({}, (global.PytmlConfig && typeof global.PytmlConfig === 'object') ? global.PytmlConfig : {}); + for (const key of ['cache', 'persist', 'preload']) { + // Accept true/false as well as 'off', 'false', '0', 'no' written as strings. + if (typeof cfg[key] === 'string') cfg[key] = !FALSE_WORDS.includes(cfg[key].trim().toLowerCase()); + } + if (SCRIPT_TAG && SCRIPT_TAG.hasAttribute) { + const flag = (name) => { + if (!SCRIPT_TAG.hasAttribute(name)) return undefined; + return !FALSE_WORDS.includes(String(SCRIPT_TAG.getAttribute(name)).trim().toLowerCase()); + }; + for (const key of ['cache', 'persist', 'preload']) { + const value = flag(`data-${key}`); + if (value !== undefined) cfg[key] = value; + } + } + return cfg; + } + const CONFIG = readConfig(); + + // --- Persistent Pyodide cache --------------------------------------------- + // Pyodide's big files (pyodide.asm.wasm, python_stdlib.zip, pyodide-lock.json + // and package wheels such as NumPy) are stored in the browser's Cache Storage + // the first time a page loads them, then served from disk afterwards. + // + // Browsers partition all storage and HTTP caches by top-level site, so a copy + // cached for site A can never be reused by site B. This cache therefore works + // per site: every page and every return visit on the same origin is instant + // after the first load. (Cookies are limited to ~4 KB and cannot hold Pyodide.) + const CACHE_PREFIX = 'pytml-pyodide-'; + const CACHE_NAME = `${CACHE_PREFIX}${PYODIDE_VERSION}`; + const CORE_FILES = ['pyodide-lock.json', 'python_stdlib.zip', 'pyodide.asm.wasm']; + const cacheStats = { hits: 0, misses: 0, stored: 0, errors: 0 }; + const pendingPuts = new Set(); + let _cachePrefixes = []; + let _fetchPatched = false; + let _cacheDisabled = false; + + function cacheSupported() { + try { + return typeof caches !== 'undefined' && typeof caches.open === 'function' && typeof Response !== 'undefined'; + } catch (_) { return false; } + } + + async function openPyodideCache() { + if (_cacheDisabled || !cacheSupported()) return null; + try { return await caches.open(CACHE_NAME); } + catch (_) { _cacheDisabled = true; return null; } // file://, sandboxed iframes, private modes + } + + function requestInfo(input, init) { + try { + const url = typeof input === 'string' ? input : (input && input.href) || (input && input.url) || ''; + const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase(); + let ranged = false; + const headers = (init && init.headers) || (input && input.headers); + if (headers) { + ranged = typeof headers.has === 'function' ? headers.has('range') + : Object.keys(headers).some((k) => k.toLowerCase() === 'range'); + } + return { url: String(url), method, ranged }; + } catch (_) { return { url: '', method: '', ranged: true }; } + } + + function installPyodideCache(indexURL) { + if (_cacheDisabled || !cacheSupported() || typeof global.fetch !== 'function') return false; + for (const prefix of [indexURL, PYODIDE_INDEX]) if (prefix && !_cachePrefixes.includes(prefix)) _cachePrefixes.push(prefix); + if (_fetchPatched) return true; + _fetchPatched = true; + const nativeFetch = global.fetch.bind(global); + + global.fetch = async function pytmlCachedFetch(input, init) { + const { url, method, ranged } = requestInfo(input, init); + // Only versioned Pyodide assets, never .mjs/.js loader scripts (those are + // loaded by import()/ +const SCRIPT_TAG = (typeof document !== 'undefined' && document.currentScript) || null; +const FALSE_WORDS = ['off', 'false', '0', 'no', 'none']; +function readConfig() { +const cfg = Object.assign({}, (global.PytmlConfig && typeof global.PytmlConfig === 'object') ? global.PytmlConfig : {}); +for (const key of ['cache', 'persist', 'preload']) { +// Accept true/false as well as 'off', 'false', '0', 'no' written as strings. +if (typeof cfg[key] === 'string') cfg[key] = !FALSE_WORDS.includes(cfg[key].trim().toLowerCase()); +} +if (SCRIPT_TAG && SCRIPT_TAG.hasAttribute) { +const flag = (name) => { +if (!SCRIPT_TAG.hasAttribute(name)) return undefined; +return !FALSE_WORDS.includes(String(SCRIPT_TAG.getAttribute(name)).trim().toLowerCase()); +}; +for (const key of ['cache', 'persist', 'preload']) { +const value = flag(`data-${key}`); +if (value !== undefined) cfg[key] = value; +} +} +return cfg; +} +const CONFIG = readConfig(); +// --- Persistent Pyodide cache --------------------------------------------- +// Pyodide's big files (pyodide.asm.wasm, python_stdlib.zip, pyodide-lock.json +// and package wheels such as NumPy) are stored in the browser's Cache Storage +// the first time a page loads them, then served from disk afterwards. +// +// Browsers partition all storage and HTTP caches by top-level site, so a copy +// cached for site A can never be reused by site B. This cache therefore works +// per site: every page and every return visit on the same origin is instant +// after the first load. (Cookies are limited to ~4 KB and cannot hold Pyodide.) +const CACHE_PREFIX = 'pytml-pyodide-'; +const CACHE_NAME = `${CACHE_PREFIX}${PYODIDE_VERSION}`; +const CORE_FILES = ['pyodide-lock.json', 'python_stdlib.zip', 'pyodide.asm.wasm']; +const cacheStats = { hits: 0, misses: 0, stored: 0, errors: 0 }; +const pendingPuts = new Set(); +let _cachePrefixes = []; +let _fetchPatched = false; +let _cacheDisabled = false; +function cacheSupported() { +try { +return typeof caches !== 'undefined' && typeof caches.open === 'function' && typeof Response !== 'undefined'; +} catch (_) { return false; } +} +async function openPyodideCache() { +if (_cacheDisabled || !cacheSupported()) return null; +try { return await caches.open(CACHE_NAME); } +catch (_) { _cacheDisabled = true; return null; } // file://, sandboxed iframes, private modes +} +function requestInfo(input, init) { +try { +const url = typeof input === 'string' ? input : (input && input.href) || (input && input.url) || ''; +const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase(); +let ranged = false; +const headers = (init && init.headers) || (input && input.headers); +if (headers) { +ranged = typeof headers.has === 'function' ? headers.has('range') +: Object.keys(headers).some((k) => k.toLowerCase() === 'range'); +} +return { url: String(url), method, ranged }; +} catch (_) { return { url: '', method: '', ranged: true }; } +} +function installPyodideCache(indexURL) { +if (_cacheDisabled || !cacheSupported() || typeof global.fetch !== 'function') return false; +for (const prefix of [indexURL, PYODIDE_INDEX]) if (prefix && !_cachePrefixes.includes(prefix)) _cachePrefixes.push(prefix); +if (_fetchPatched) return true; +_fetchPatched = true; +const nativeFetch = global.fetch.bind(global); +global.fetch = async function pytmlCachedFetch(input, init) { +const { url, method, ranged } = requestInfo(input, init); +// Only versioned Pyodide assets, never .mjs/.js loader scripts (those are +// loaded by import()/ + + + +

Gamepad Tester

+
Connect a controller and press any button.
+ + + + +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") + + +

← Back to demos

+ + diff --git a/examples/game-sound.html b/examples/game-sound.html new file mode 100644 index 0000000..5822d4e --- /dev/null +++ b/examples/game-sound.html @@ -0,0 +1,72 @@ + + + + + + Pytml Sound Lab + + + + +

Sound Lab

+

Retro sound effects built into Pytml. No audio files needed.

+ +
+ + + + +
+ +

Make your own

+ + + + + + + +
+ + +

+
+
+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()
+
+
+

← Back to demos

+ + diff --git a/examples/game-space-shooter.html b/examples/game-space-shooter.html new file mode 100644 index 0000000..ff11918 --- /dev/null +++ b/examples/game-space-shooter.html @@ -0,0 +1,165 @@ + + + + + + Pytml Space Shooter + + + + + +
+

Arrows / WASD move  ·  Space / gamepad A fires  ·  P pauses

+ + +import math +import random +from pytml import Canvas, loop, controls, dpad, touch_button, sfx, HighScores, Vec2, clamp, circle_overlap, vibrate + +W, H = 360, 480 +screen = Canvas("screen", W, H, fit=True) +dpad("dpad") +touch_button("fire", "FIRE") + +controls.use_defaults() +controls.bind("left", "touch:dpad.left") +controls.bind("right", "touch:dpad.right") +controls.bind("fire", "space", "z", "pad:a", "pad:rt", "touch:fire") + +scores = HighScores("pytml-space-shooter", limit=5) +stars = [[random.uniform(0, W), random.uniform(0, H), random.uniform(20, 90)] for _ in range(60)] +g = {} + + +def reset(): + g.update(state="play", paused=False, x=W / 2, cooldown=0.0, spawn=0.0, score=0, lives=3, + invuln=0.0, bullets=[], enemies=[], sparks=[], rank=None, time=0.0) + + +def explode(x, y, color, n=14): + for _ in range(n): + speed = random.uniform(40, 180) + g["sparks"].append([x, y, speed * random.uniform(-1, 1), speed * random.uniform(-1, 1), random.uniform(0.3, 0.7), color]) + + +def update(dt): + for st in stars: # parallax stars never stop + st[1] = (st[1] + st[2] * dt) % H + + if g["state"] == "over": + if controls.pressed("action") or controls.pressed("fire"): + reset() + return + if controls.pressed("pause"): + g["paused"] = not g["paused"] + if g["paused"]: + return + + g["time"] += dt + g["x"] = clamp(g["x"] + controls.axis("left", "right") * 230 * dt, 18, W - 18) + g["cooldown"] -= dt + g["invuln"] = max(0.0, g["invuln"] - dt) + + if controls.down("fire") and g["cooldown"] <= 0: + g["bullets"].append([g["x"], H - 56]) + g["cooldown"] = 0.17 + sfx.play("laser", 0.12) + + g["spawn"] -= dt + if g["spawn"] <= 0: + g["enemies"].append({"x": random.uniform(20, W - 20), "y": -20.0, "phase": random.uniform(0, 6.28), "dead": False}) + g["spawn"] = max(0.25, 0.9 - g["score"] / 900) + + speed = 70 + g["score"] / 8 + for b in g["bullets"]: + b[1] -= 440 * dt + for e in g["enemies"]: + e["y"] += speed * dt + e["x"] = clamp(e["x"] + math.sin(g["time"] * 2 + e["phase"]) * 60 * dt, 14, W - 14) + + for b in g["bullets"]: + for e in g["enemies"]: + if not e["dead"] and circle_overlap(b[0], b[1], 3, e["x"], e["y"], 14): + b[1] = -100 + e["dead"] = True + g["score"] += 10 + explode(e["x"], e["y"], "#ff9f43", 8) + sfx.play("hit", 0.15) + break + g["bullets"] = [b for b in g["bullets"] if b[1] > -20] + + alive = [] + for e in g["enemies"]: + if e["dead"]: + continue + if g["invuln"] <= 0 and circle_overlap(g["x"], H - 40, 12, e["x"], e["y"], 14): + explode(g["x"], H - 40, "#4aa8ff", 24) + sfx.play("explosion", 0.3) + vibrate(120) + g["invuln"] = 1.5 + g["lives"] -= 1 + elif e["y"] > H + 20: # got past the ship + sfx.play("error", 0.15) + g["lives"] -= 1 + else: + alive.append(e) + g["enemies"] = alive + + if g["lives"] <= 0: + g["state"] = "over" + g["rank"] = scores.submit(g["score"], "YOU") + sfx.play("lose", 0.25) + + for s in g["sparks"]: + s[0] += s[2] * dt + s[1] += s[3] * dt + s[4] -= dt + g["sparks"] = [s for s in g["sparks"] if s[4] > 0] + + +def draw(): + screen.clear("#05060a") + for sx, sy, sp in stars: + v = int(80 + sp) + screen.rect(sx, sy, 2, 2, (v, v, v + 40)) + for b in g["bullets"]: + screen.rect(b[0] - 1.5, b[1] - 8, 3, 12, "#7df9ff") + for e in g["enemies"]: + screen.circle(e["x"], e["y"], 14, "#e5484d") + screen.circle(e["x"] - 5, e["y"] - 2, 3, "#fff") + screen.circle(e["x"] + 5, e["y"] - 2, 3, "#fff") + for sx, sy, _, _, life, color in g["sparks"]: + screen.rect(sx, sy, 3, 3, color) + if g["state"] == "play" and (g["invuln"] <= 0 or int(g["time"] * 14) % 2): + x, y = g["x"], H - 40 + screen.polygon([(x, y - 18), (x + 14, y + 14), (x, y + 8), (x - 14, y + 14)], "#4aa8ff") + + screen.text(f"SCORE {g['score']}", 10, 8, "#e6edf3", 15, bold=True) + screen.text(f"BEST {scores.best or 0}", W / 2, 8, "#8b949e", 13, align="center") + screen.text("♥" * max(0, g["lives"]), W - 10, 8, "#e5484d", 15, align="right") + + if g["paused"]: + screen.text("PAUSED", W / 2, H / 2, "#fff", 28, align="center", baseline="middle", bold=True) + if g["state"] == "over": + screen.text("GAME OVER", W / 2, H / 2 - 40, "#fff", 30, align="center", baseline="middle", bold=True) + if g["rank"]: + screen.text(f"New high score! Rank #{g['rank']}", W / 2, H / 2, "#ffd166", 16, align="center", baseline="middle") + screen.text("Press Space / FIRE to play again", W / 2, H / 2 + 40, "#8b949e", 14, align="center", baseline="middle") + + +reset() +loop(update, render=draw) + + +

← Back to demos

+ + diff --git a/examples/game-sprites.html b/examples/game-sprites.html new file mode 100644 index 0000000..b1f9f51 --- /dev/null +++ b/examples/game-sprites.html @@ -0,0 +1,60 @@ + + + + + + Pytml Sprites + + + + +

Sprite Animation

+ +

Left / Right to walk. This sprite sheet is drawn in code; use await load_image("hero.png") for your own art.

+ + +from pytml import Canvas, SpriteSheet, Animation, loop, controls, clamp + +# --- build a 4-frame sprite sheet in code (16x16 per frame) ------------------- +sheet_canvas = Canvas.create(64, 16, hidpi=False) +for frame in range(4): + ox = frame * 16 + bob = (0, -1, 0, -1)[frame] + leg = (0, 3, 0, -3)[frame] + sheet_canvas.rect(ox + 4, 4 + bob, 8, 8, "#f6c177") # body + sheet_canvas.rect(ox + 5, 6 + bob, 2, 2, "#191724") # eyes + sheet_canvas.rect(ox + 9, 6 + bob, 2, 2, "#191724") + sheet_canvas.rect(ox + 4 + leg // 2, 12, 3, 3, "#eb6f92") # feet + sheet_canvas.rect(ox + 9 - leg // 2, 12, 3, 3, "#eb6f92") + +sheet = SpriteSheet(sheet_canvas, 16, 16) +walk = Animation(sheet, [0, 1, 2, 3], fps=8) +idle = Animation(sheet, [0], fps=1) + +screen = Canvas("screen", 320, 160, pixelated=True, fit=True) +controls.use_defaults() +x, facing_left = 150.0, False + + +@loop +def update(dt): + global x, facing_left + move = controls.axis("left", "right") + x = clamp(x + move * 90 * dt, 0, 320 - 64) + if move: + facing_left = move < 0 + anim = walk if move else idle + anim.update(dt) + + screen.clear("#1f1d2e") + screen.rect(0, 120, 320, 40, "#26233a") + anim.draw(screen, x, 56, 64, 64, flip_x=facing_left) # 4x scale, crisp pixels + + +

← Back to demos

+ + diff --git a/examples/game-starter.html b/examples/game-starter.html new file mode 100644 index 0000000..be775c0 --- /dev/null +++ b/examples/game-starter.html @@ -0,0 +1,64 @@ + + + + + + Pytml Game Starter + + + + +

Game Starter

+ +
+

Move: arrows / WASD / gamepad stick / on-screen D-pad  ·  Action: Space / gamepad A / on-screen button

+ + +from pytml import Canvas, loop, controls, dpad, touch_button, sfx, Vec2, clamp + +screen = Canvas("screen", 480, 320, fit=True) +dpad("dpad") +touch_button("jump", "A") + +# One set of actions, three kinds of input. +controls.use_defaults() +controls.bind("left", "touch:dpad.left") +controls.bind("right", "touch:dpad.right") +controls.bind("up", "touch:dpad.up") +controls.bind("down", "touch:dpad.down") +controls.bind("action", "touch:jump") + +player = Vec2(240, 160) +SPEED = 200 +pulse = 0.0 + + +@loop +def update(dt): + global player, pulse + player += controls.vector() * SPEED * dt # diagonals are not faster + player = Vec2(clamp(player.x, 16, 464), clamp(player.y, 16, 304)) + + if controls.pressed("action"): + sfx.play("coin") + pulse = 1.0 + pulse = max(0.0, pulse - dt * 3) + + screen.clear("#111827") + screen.circle(player.x, player.y, 16 + pulse * 18, (80, 170, 255, 0.25 + pulse * 0.4)) + screen.circle(player.x, player.y, 12, "#4aa8ff") + screen.text("Pytml Game Kit", 10, 8, "#8b949e", 14) + screen.text(f"{update.fps:.0f} fps", 470, 8, "#8b949e", 14, align="right") + + +

← Back to demos

+ + diff --git a/index.html b/index.html index f888e56..cbcb5ba 100644 --- a/index.html +++ b/index.html @@ -5,7 +5,7 @@ Pytml – Python + HTML in the Browser - + @@ -51,13 +51,13 @@ "mainEntityOfPage": { "@type": "WebPage", "@id": "https://pytml.js.org/" }, "name": "Pytml", "alternateName": "Python in HTML Bridge", - "headline": "Pytml 2.5 – Python + HTML in the Browser", - "description": "Pytml 2.5 is a zero-config JavaScript bridge that runs Python in HTML using Pyodide and WebAssembly. It adds DOM interaction, browser input, numbered inline UI controls, events and micropip-backed package support.", + "headline": "Pytml 2.6 – Python + HTML in the Browser", + "description": "Pytml 2.6 is a zero-config JavaScript bridge that runs Python in HTML using Pyodide and WebAssembly. It injects the pytml helper module at startup and embeds the Game Kit for lazy first-use compilation.", "keywords": ["Pytml", "PyScript alternative", "Flask alternative", "Python in Browser", "Zero Config Python"], "applicationCategory": "DeveloperApplication", - "softwareVersion": "2.5.1", + "softwareVersion": "2.6.0", "datePublished": "2026-06-04", - "dateModified": "2026-10-02", + "dateModified": "2026-11-29", "license": "https://github.com/NodeX-AR/Pytml/blob/main/LICENSE", "url": "https://pytml.js.org/", "author": { @@ -177,7 +177,7 @@ { "@type": "FAQPage", "mainEntity": [ - { "@type": "Question", "name": "What is the actual bundle size of Pytml?", "acceptedAnswer": { "@type": "Answer", "text": "Pytml loads its JavaScript bridge immediately and loads Pyodide 0.314.0.7 from the configured CDN during startup. The exact transfer size varies with the browser and cache state." } }, + { "@type": "Question", "name": "What is the actual bundle size of Pytml?", "acceptedAnswer": { "@type": "Answer", "text": "Pytml ships a small JavaScript bridge and loads Pyodide 314.0.7 lazily from CDN on first Python execution, then reuses the browser cache. Exact transfer size varies by browser and cache state." } }, { "@type": "Question", "name": "Can I use Pytml with React, Vue, or other JS frameworks?", "acceptedAnswer": { "@type": "Answer", "text": "Yes. Pytml is framework-agnostic. You can drop the script tag in any HTML page, including those generated by React or Vue. It scans the DOM for tags after the framework renders." } }, { "@type": "Question", "name": "What Python packages are supported?", "acceptedAnswer": { "@type": "Answer", "text": "Pytml uses Pyodide's package environment and micropip workflow. Packages available in the Pyodide distribution, including NumPy, pandas and Matplotlib, can be used when compatible with the browser runtime." } }, { "@type": "Question", "name": "How does Pytml handle errors and debugging?", "acceptedAnswer": { "@type": "Answer", "text": "Python tracebacks are captured and rendered directly in the browser terminal box. Syntax errors, runtime exceptions, and import errors all appear with line numbers and stack traces, just like a local Python REPL." } }, @@ -1047,7 +1047,7 @@
- Pytml 2.5 — powered by Pyodide + Pytml 2.6 — powered by Pyodide

Run @@ -1085,7 +1085,7 @@

Pyodide from CDN

The full Python runtime loads lazily in the background, compiled to WebAssembly.

import pyodide
-
→ 0.314.0.7
+
→ 314.0.7
→ ~6MB (cached)
diff --git a/package.json b/package.json index 89ac05b..07acfb2 100644 --- a/package.json +++ b/package.json @@ -8,5 +8,14 @@ }, "dependencies": { "@upstash/redis": "^1.34.3" + }, + "scripts": { + "build": "node tools/build.mjs", + "test": "node --test tests/runtime.test.js", + "test:integration": "node tests/integration/run.mjs" + }, + "devDependencies": { + "jsdom": "^26.1.0", + "pyodide": "314.0.7" } } diff --git a/pytml.js b/pytml.js index 035bd10..7d0d5df 100644 --- a/pytml.js +++ b/pytml.js @@ -1,14 +1,17 @@ /* - * Pytml 2.5.1 + * Pytml 2.6.0 * Python + HTML, powered by Pyodide. * - * Pytml 2.5 includes a lightweight inline UI preprocessor for blocks. + * Pytml 2.6 adds a persistent Pyodide cache (Cache Storage API) and the + * Pytml Game Kit (game loop, keyboard/gamepad/touch input, canvas, sprites, + * sound, collisions, save games). The Game Kit is loaded lazily, so pages + * that do not use it pay nothing. * The full document/language compiler remains planned for v3.0. */ (function (global) { 'use strict'; - const VERSION = '2.5.1'; + const VERSION = '2.6.0'; const PYODIDE_VERSION = '314.0.7'; const PYODIDE_INDEX = `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`; const PYODIDE_SCRIPT = `${PYODIDE_INDEX}pyodide.js`; @@ -16,6 +19,186 @@ const IS_FILE_PROTOCOL = typeof location !== 'undefined' && location.protocol === 'file:'; const PY_BLOCK = /^py(?:\d+)?$/i; + + // --- Configuration ------------------------------------------------------- + // Read from window.PytmlConfig (set before the script tag) and from data-* + // attributes on the + const SCRIPT_TAG = (typeof document !== 'undefined' && document.currentScript) || null; + const FALSE_WORDS = ['off', 'false', '0', 'no', 'none']; + + function readConfig() { + const cfg = Object.assign({}, (global.PytmlConfig && typeof global.PytmlConfig === 'object') ? global.PytmlConfig : {}); + for (const key of ['cache', 'persist', 'preload']) { + // Accept true/false as well as 'off', 'false', '0', 'no' written as strings. + if (typeof cfg[key] === 'string') cfg[key] = !FALSE_WORDS.includes(cfg[key].trim().toLowerCase()); + } + if (SCRIPT_TAG && SCRIPT_TAG.hasAttribute) { + const flag = (name) => { + if (!SCRIPT_TAG.hasAttribute(name)) return undefined; + return !FALSE_WORDS.includes(String(SCRIPT_TAG.getAttribute(name)).trim().toLowerCase()); + }; + for (const key of ['cache', 'persist', 'preload']) { + const value = flag(`data-${key}`); + if (value !== undefined) cfg[key] = value; + } + } + return cfg; + } + const CONFIG = readConfig(); + + // --- Persistent Pyodide cache --------------------------------------------- + // Pyodide's big files (pyodide.asm.wasm, python_stdlib.zip, pyodide-lock.json + // and package wheels such as NumPy) are stored in the browser's Cache Storage + // the first time a page loads them, then served from disk afterwards. + // + // Browsers partition all storage and HTTP caches by top-level site, so a copy + // cached for site A can never be reused by site B. This cache therefore works + // per site: every page and every return visit on the same origin is instant + // after the first load. (Cookies are limited to ~4 KB and cannot hold Pyodide.) + const CACHE_PREFIX = 'pytml-pyodide-'; + const CACHE_NAME = `${CACHE_PREFIX}${PYODIDE_VERSION}`; + const CORE_FILES = ['pyodide-lock.json', 'python_stdlib.zip', 'pyodide.asm.wasm']; + const cacheStats = { hits: 0, misses: 0, stored: 0, errors: 0 }; + const pendingPuts = new Set(); + let _cachePrefixes = []; + let _fetchPatched = false; + let _cacheDisabled = false; + + function cacheSupported() { + try { + return typeof caches !== 'undefined' && typeof caches.open === 'function' && typeof Response !== 'undefined'; + } catch (_) { return false; } + } + + async function openPyodideCache() { + if (_cacheDisabled || !cacheSupported()) return null; + try { return await caches.open(CACHE_NAME); } + catch (_) { _cacheDisabled = true; return null; } // file://, sandboxed iframes, private modes + } + + function requestInfo(input, init) { + try { + const url = typeof input === 'string' ? input : (input && input.href) || (input && input.url) || ''; + const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase(); + let ranged = false; + const headers = (init && init.headers) || (input && input.headers); + if (headers) { + ranged = typeof headers.has === 'function' ? headers.has('range') + : Object.keys(headers).some((k) => k.toLowerCase() === 'range'); + } + return { url: String(url), method, ranged }; + } catch (_) { return { url: '', method: '', ranged: true }; } + } + + function installPyodideCache(indexURL) { + if (_cacheDisabled || !cacheSupported() || typeof global.fetch !== 'function') return false; + for (const prefix of [indexURL, PYODIDE_INDEX]) if (prefix && !_cachePrefixes.includes(prefix)) _cachePrefixes.push(prefix); + if (_fetchPatched) return true; + _fetchPatched = true; + const nativeFetch = global.fetch.bind(global); + + global.fetch = async function pytmlCachedFetch(input, init) { + const { url, method, ranged } = requestInfo(input, init); + // Only versioned Pyodide assets, never .mjs/.js loader scripts (those are + // loaded by import()/ +const SCRIPT_TAG = (typeof document !== 'undefined' && document.currentScript) || null; +const FALSE_WORDS = ['off', 'false', '0', 'no', 'none']; +function readConfig() { +const cfg = Object.assign({}, (global.PytmlConfig && typeof global.PytmlConfig === 'object') ? global.PytmlConfig : {}); +for (const key of ['cache', 'persist', 'preload']) { +// Accept true/false as well as 'off', 'false', '0', 'no' written as strings. +if (typeof cfg[key] === 'string') cfg[key] = !FALSE_WORDS.includes(cfg[key].trim().toLowerCase()); +} +if (SCRIPT_TAG && SCRIPT_TAG.hasAttribute) { +const flag = (name) => { +if (!SCRIPT_TAG.hasAttribute(name)) return undefined; +return !FALSE_WORDS.includes(String(SCRIPT_TAG.getAttribute(name)).trim().toLowerCase()); +}; +for (const key of ['cache', 'persist', 'preload']) { +const value = flag(`data-${key}`); +if (value !== undefined) cfg[key] = value; +} +} +return cfg; +} +const CONFIG = readConfig(); +// --- Persistent Pyodide cache --------------------------------------------- +// Pyodide's big files (pyodide.asm.wasm, python_stdlib.zip, pyodide-lock.json +// and package wheels such as NumPy) are stored in the browser's Cache Storage +// the first time a page loads them, then served from disk afterwards. +// +// Browsers partition all storage and HTTP caches by top-level site, so a copy +// cached for site A can never be reused by site B. This cache therefore works +// per site: every page and every return visit on the same origin is instant +// after the first load. (Cookies are limited to ~4 KB and cannot hold Pyodide.) +const CACHE_PREFIX = 'pytml-pyodide-'; +const CACHE_NAME = `${CACHE_PREFIX}${PYODIDE_VERSION}`; +const CORE_FILES = ['pyodide-lock.json', 'python_stdlib.zip', 'pyodide.asm.wasm']; +const cacheStats = { hits: 0, misses: 0, stored: 0, errors: 0 }; +const pendingPuts = new Set(); +let _cachePrefixes = []; +let _fetchPatched = false; +let _cacheDisabled = false; +function cacheSupported() { +try { +return typeof caches !== 'undefined' && typeof caches.open === 'function' && typeof Response !== 'undefined'; +} catch (_) { return false; } +} +async function openPyodideCache() { +if (_cacheDisabled || !cacheSupported()) return null; +try { return await caches.open(CACHE_NAME); } +catch (_) { _cacheDisabled = true; return null; } // file://, sandboxed iframes, private modes +} +function requestInfo(input, init) { +try { +const url = typeof input === 'string' ? input : (input && input.href) || (input && input.url) || ''; +const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase(); +let ranged = false; +const headers = (init && init.headers) || (input && input.headers); +if (headers) { +ranged = typeof headers.has === 'function' ? headers.has('range') +: Object.keys(headers).some((k) => k.toLowerCase() === 'range'); +} +return { url: String(url), method, ranged }; +} catch (_) { return { url: '', method: '', ranged: true }; } +} +function installPyodideCache(indexURL) { +if (_cacheDisabled || !cacheSupported() || typeof global.fetch !== 'function') return false; +for (const prefix of [indexURL, PYODIDE_INDEX]) if (prefix && !_cachePrefixes.includes(prefix)) _cachePrefixes.push(prefix); +if (_fetchPatched) return true; +_fetchPatched = true; +const nativeFetch = global.fetch.bind(global); +global.fetch = async function pytmlCachedFetch(input, init) { +const { url, method, ranged } = requestInfo(input, init); +// Only versioned Pyodide assets, never .mjs/.js loader scripts (those are +// loaded by import()/ + const SCRIPT_TAG = (typeof document !== 'undefined' && document.currentScript) || null; + const FALSE_WORDS = ['off', 'false', '0', 'no', 'none']; + + function readConfig() { + const cfg = Object.assign({}, (global.PytmlConfig && typeof global.PytmlConfig === 'object') ? global.PytmlConfig : {}); + for (const key of ['cache', 'persist', 'preload']) { + // Accept true/false as well as 'off', 'false', '0', 'no' written as strings. + if (typeof cfg[key] === 'string') cfg[key] = !FALSE_WORDS.includes(cfg[key].trim().toLowerCase()); + } + if (SCRIPT_TAG && SCRIPT_TAG.hasAttribute) { + const flag = (name) => { + if (!SCRIPT_TAG.hasAttribute(name)) return undefined; + return !FALSE_WORDS.includes(String(SCRIPT_TAG.getAttribute(name)).trim().toLowerCase()); + }; + for (const key of ['cache', 'persist', 'preload']) { + const value = flag(`data-${key}`); + if (value !== undefined) cfg[key] = value; + } + } + return cfg; + } + const CONFIG = readConfig(); + + // --- Persistent Pyodide cache --------------------------------------------- + // Pyodide's big files (pyodide.asm.wasm, python_stdlib.zip, pyodide-lock.json + // and package wheels such as NumPy) are stored in the browser's Cache Storage + // the first time a page loads them, then served from disk afterwards. + // + // Browsers partition all storage and HTTP caches by top-level site, so a copy + // cached for site A can never be reused by site B. This cache therefore works + // per site: every page and every return visit on the same origin is instant + // after the first load. (Cookies are limited to ~4 KB and cannot hold Pyodide.) + const CACHE_PREFIX = 'pytml-pyodide-'; + const CACHE_NAME = `${CACHE_PREFIX}${PYODIDE_VERSION}`; + const CORE_FILES = ['pyodide-lock.json', 'python_stdlib.zip', 'pyodide.asm.wasm']; + const cacheStats = { hits: 0, misses: 0, stored: 0, errors: 0 }; + const pendingPuts = new Set(); + let _cachePrefixes = []; + let _fetchPatched = false; + let _cacheDisabled = false; + + function cacheSupported() { + try { + return typeof caches !== 'undefined' && typeof caches.open === 'function' && typeof Response !== 'undefined'; + } catch (_) { return false; } + } + + async function openPyodideCache() { + if (_cacheDisabled || !cacheSupported()) return null; + try { return await caches.open(CACHE_NAME); } + catch (_) { _cacheDisabled = true; return null; } // file://, sandboxed iframes, private modes + } + + function requestInfo(input, init) { + try { + const url = typeof input === 'string' ? input : (input && input.href) || (input && input.url) || ''; + const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase(); + let ranged = false; + const headers = (init && init.headers) || (input && input.headers); + if (headers) { + ranged = typeof headers.has === 'function' ? headers.has('range') + : Object.keys(headers).some((k) => k.toLowerCase() === 'range'); + } + return { url: String(url), method, ranged }; + } catch (_) { return { url: '', method: '', ranged: true }; } + } + + function installPyodideCache(indexURL) { + if (_cacheDisabled || !cacheSupported() || typeof global.fetch !== 'function') return false; + for (const prefix of [indexURL, PYODIDE_INDEX]) if (prefix && !_cachePrefixes.includes(prefix)) _cachePrefixes.push(prefix); + if (_fetchPatched) return true; + _fetchPatched = true; + const nativeFetch = global.fetch.bind(global); + + global.fetch = async function pytmlCachedFetch(input, init) { + const { url, method, ranged } = requestInfo(input, init); + // Only versioned Pyodide assets, never .mjs/.js loader scripts (those are + // loaded by import()/