feat(tetris-3d): clean-room 3D block puzzle plugin for ScorpioX Bot
Single dependency-free C99 binary serving three modes: --meta / SX_PLUGIN_META=1 discovery metadata ?action=scores|save_score|format=json JSON score API GET self-contained 3D game UI Gameplay: software-projected isometric cubes (no WebGL, no CDN, no network requests), ghost piece, next-piece queue, hold, wall kicks, level speed curve, classic scoring, keyboard and touch input, dark and light themes, fluid layout down to a 390 px viewport. High scores persist to .tetris_scores.json in the node plugin directory; the API is gated by require_node_auth() accepting X-Bot-Password, Bearer and ?pwd=. tests/run.sh: 114 offline assertions (metadata, score store ordering and the ten-entry cap, POST and percent-decoded bodies, unwritable store, all three credential forms, full HTML contract, emoji audit, full-history secret and private-address scan). tests/e2e.py: Playwright at 1440/1024/390 plus dark and light, asserting no overflow, painted canvases and responsive gameplay.
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-11 10:52:29
Commit299d12fb
Changed files
.gitignore+14−0■■■■■
LICENSE+21−0■■■■■
Makefile+69−0■■■■■
README.md+142−0■■■■■
build.ps1+47−0■■■■■
plugin.json+12−0■■■■■
release-dist.sh+364−0■■■■■
src/plugin_tetris_3d.c+458−0■■■■■
src/ui_html.h+583−0■■■■■
tests/e2e.py+207−0■■■■■
tests/run.sh+307−0■■■■■
11 files+2224−0
Diff
.gitignore+14−0■■■■■
11new file mode 100644
index 0000000..ec3341d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,14 @@
1+/plugin_tetris_3d
2+/plugin_tetris_3d.musl
3+/plugin_tetris_3d.arm64
4+/plugin_tetris_3d.exe
5+/plugin_tetris_3d.macos-arm64
6+/plugin_tetris_3d.macos-x86_64
7+*.o
8+*.obj
9+*.tmp
10+*.log
11+__pycache__/
12+*.pyc
13+*.dSYM
14+bin/
LICENSE+21−0■■■■■
11new file mode 100644
index 0000000..ef80120
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+69−0■■■■■
11new file mode 100644
index 0000000..59f1c9d
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,69 @@
1+# plugin_tetris_3d - ScorpioX Bot open-source 3D block game
2+#
3+# Targets:
4+# make native build -> ./plugin_tetris_3d
5+# make musl static musl x86_64 -> ./plugin_tetris_3d.musl
6+# make arm64 static aarch64 -> ./plugin_tetris_3d.arm64
7+# make win64 MinGW-w64 static PE -> ./plugin_tetris_3d.exe
8+# make macos Apple clang (run on macOS)
9+# make test build + run tests/run.sh
10+# make clean
11+
12+CC ?= cc
13+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings
14+MUSL_CC ?= musl-gcc
15+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
16+ARM_CC ?= aarch64-linux-gnu-gcc
17+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
18+WIN_CC ?= x86_64-w64-mingw32-gcc
19+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
20+SRC := src/plugin_tetris_3d.c
21+BIN := plugin_tetris_3d
22+EXE := plugin_tetris_3d.exe
23+PREFIX ?= $(HOME)/.scorpiox/plugins
24+
25+.PHONY: all native musl arm64 win64 macos install test clean help
26+
27+all: native
28+
29+native: $(BIN)
30+
31+$(BIN): $(SRC) src/ui_html.h
32+ @echo "==> native build ($(CC))"
33+ $(CC) $(CFLAGS) -o $(BIN) $(SRC)
34+
35+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
36+musl: $(SRC) src/ui_html.h
37+ @echo "==> static musl build ($(MUSL_CC))"
38+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC)
39+
40+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
41+arm64: $(SRC) src/ui_html.h
42+ @echo "==> static arm64 build ($(ARM_CC))"
43+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC)
44+
45+# Native Win64 static PE - runs on any Windows 10/11 x64 node
46+win64: $(SRC) src/ui_html.h
47+ @echo "==> MinGW-w64 build ($(WIN_CC))"
48+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC)
49+
50+# Apple clang build (run this on macOS)
51+macos: $(SRC) src/ui_html.h
52+ @echo "==> Apple clang build"
53+ $(CC) -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o $(BIN) $(SRC)
54+
55+install: native
56+ @echo "==> install to $(PREFIX)"
57+ mkdir -p "$(PREFIX)"
58+ cp $(BIN) "$(PREFIX)/"
59+ chmod +x "$(PREFIX)/$(BIN)"
60+
61+test: native
62+ @sh tests/run.sh
63+
64+clean:
65+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64
66+ rm -rf bin
67+
68+help:
69+ @echo "make | make musl | make arm64 | make win64 | make macos | make install | make test | make clean"
README.md+142−0■■■■■
11new file mode 100644
index 0000000..b6e21aa
--- /dev/null
+++ b/README.md
@@ -0,0 +1,142 @@
1+# plugin_tetris_3d
2+
3+A 3D block-stacking puzzle game for a ScorpioX Bot node — a single clean-room C99
4+binary, MIT licensed, with no dependency beyond libc.
5+
6+It serves a complete game UI: isometric cubes with real depth and shading,
7+ghost piece, next-piece preview, hold queue, keyboard and touch controls, and a
8+local high-score table. Everything is rendered by a small software 3D projector
9+onto a 2D canvas, so there is no WebGL requirement, no CDN script, and no
10+network request of any kind — the UI works on an offline node.
11+
12+## What it writes
13+
14+One small JSON file, and nothing else:
15+
16+```
17+<plugin dir>/.tetris_scores.json {"scores":[1200,900,300]}
18+```
19+
20+`<plugin dir>` is `$BOT_PLUGIN_DIR` when set, otherwise
21+`%LOCALAPPDATA%\scorpiox\plugins` on Windows and `~/.scorpiox/plugins`
22+(`/workspace/.scorpiox/plugins` on BotCloud) on POSIX. `SX_TETRIS_SCORES`
23+overrides the full path, which is what the test suite uses.
24+
25+The file holds the best ten scores, newest-best first. Writes are atomic at the
26+plugin level: the whole table is re-serialised on each accepted score, so a
27+truncated file can never leave a half-written entry.
28+
29+## Three modes
30+
31+### 1. Discovery
32+
33+```sh
34+./plugin_tetris_3d --meta
35+# {"name":"tetris","desc":"3D block game"}
36+```
37+
38+`SX_PLUGIN_META=1` does the same. This route stays unauthenticated so `/plugins`
39+discovery works.
40+
41+### 2. JSON API
42+
43+```sh
44+./plugin_tetris_3d '?action=scores'
45+./plugin_tetris_3d '?action=save_score&val=1200'
46+curl -d 'val=9900' 'http://node:8150/plugin_tetris_3d?action=save_score'
47+```
48+
49+```json
50+{"ok":true,"plugin":"plugin_tetris_3d","version":"1.0.0",
51+ "highscore":1200,"scores":[1200,900,300]}
52+```
53+
54+`action=scores` (aliases `highscore`, `leaderboard`) reads the table.
55+`action=save_score` inserts a score and returns the updated table; a value that
56+is not a positive integer is refused with `{"ok":false,"error":"invalid_score"}`.
57+Any `POST` whose body carries `val=` or `score=` is treated as a save, and
58+`?format=json` returns the table. If the score file cannot be written the
59+response is `{"ok":false,"error":"score_store_unwritable", ...}` rather than a
60+silent success.
61+
62+The API is gated by `require_node_auth()` exactly like every other node plugin:
63+`X-Bot-Password`, `Authorization: Bearer <pwd>`, or `?pwd=` are all accepted, and
64+the process 401s only when `BOT_PASSWORD` is set and none of the three match.
65+`--meta` stays unauthenticated.
66+
67+### 3. HTML UI
68+
69+A `GET` without an action serves the game in a single self-contained document.
70+`?embed=1` drops the outer chrome so it fits the Chat floating window; the layout
71+is fluid down to a 390 px viewport and short heights.
72+
73+Controls:
74+
75+| Input | Action |
76+|---|---|
77+| Left / Right or `A` / `D` | move |
78+| Up or `W` / `X` | rotate clockwise |
79+| `Z` | rotate counter-clockwise |
80+| Down or `S` | soft drop |
81+| Space | hard drop |
82+| `C` | hold |
83+| `P` / `Esc` | pause |
84+| swipe left / right on the board | move (touch) |
85+| tap the board | rotate (touch) |
86+
87+Scoring is single 100, double 300, triple 500, tetris 800, multiplied by the
88+level; soft drop scores 1 per row and hard drop 2 per row. Level rises every ten
89+lines and the gravity interval tightens from 800 ms toward a 90 ms floor.
90+
91+## Build
92+
93+```sh
94+make # native
95+make musl # static musl x86_64, the universal Linux artifact
96+make arm64 # static aarch64
97+make win64 # static Win64 PE via MinGW-w64
98+make macos # Apple clang, run this on macOS
99+make test # build and run the offline assertion suite
100+```
101+
102+On Windows:
103+
104+```powershell
105+powershell -ExecutionPolicy Bypass -File build.ps1
106+```
107+
108+`src/ui_html.h` is generated from the single-file UI template and is committed,
109+so no generator step is needed to build.
110+
111+## Install on a node
112+
113+```sh
114+make && make install PREFIX=$HOME/.scorpiox/plugins
115+```
116+
117+Or through the node installer once published:
118+
119+```sh
120+curl -X POST 'http://127.0.0.1:8150/plugin_manage?action=install' \
121+ -H "X-Bot-Password: $BOT_PASSWORD" \
122+ -d '{"slug":"tetris-3d","id":"plugin_tetris_3d","mode":"prebuilt","version":"1.0.0"}'
123+```
124+
125+## Tests
126+
127+```sh
128+sh tests/run.sh # 114 offline assertions, no network, no real score file
129+python3 tests/e2e.py # Playwright: 1440 / 1024 / 390 viewports, dark + light
130+```
131+
132+The offline suite covers metadata shape, the score store (ordering, the ten-entry
133+cap, unwritable store, percent-decoded and POST bodies), all three credential
134+forms, the full HTML contract, an emoji audit, and a full-git-history scan for
135+tokens and private addresses. The Playwright run asserts no horizontal or
136+vertical overflow at any viewport, that all three canvases have backing pixels
137+and actually painted, that the HUD renders, that a hard drop moves the score, and
138+that the touch pad is reachable at 390 px.
139+
140+## License
141+
142+MIT. Copyright (c) 2026 SCORPIOX INC.
build.ps1+47−0■■■■■
11new file mode 100644
index 0000000..babc475
--- /dev/null
+++ b/build.ps1
@@ -0,0 +1,47 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_tetris_3d
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_tetris_3d.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin).
8+
9+$ErrorActionPreference = "Stop"
10+$ScriptDir = $PSScriptRoot
11+Push-Location $ScriptDir
12+try {
13+ $Src = Join-Path $ScriptDir "src\plugin_tetris_3d.c"
14+ $Hdr = Join-Path $ScriptDir "src\ui_html.h"
15+ $Out = Join-Path $ScriptDir "plugin_tetris_3d.exe"
16+ $Cc = "x86_64-w64-mingw32-gcc"
17+
18+ if (-not (Test-Path $Src)) { throw "source not found: $Src" }
19+ if (-not (Test-Path $Hdr)) { throw "generated UI header not found: $Hdr" }
20+
21+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
22+ $Candidate = $null
23+ if (Get-Command $Cc -ErrorAction SilentlyContinue) {
24+ $Candidate = $Cc
25+ } elseif (Test-Path "C:\gcc16\bin\gcc.exe") {
26+ $Candidate = "C:\gcc16\bin\gcc.exe"
27+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
28+ $Candidate = "gcc"
29+ }
30+ if (-not $Candidate) { throw "no C compiler found (need x86_64-w64-mingw32-gcc, C:\gcc16\bin\gcc.exe or gcc on PATH)" }
31+
32+ Write-Host "Compiling plugin_tetris_3d.exe with $Candidate ..."
33+ & $Candidate -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o $Out $Src
34+ if ($LASTEXITCODE -ne 0) { throw "compile failed with exit code $LASTEXITCODE" }
35+
36+ $bytes = [System.IO.File]::ReadAllBytes($Out)
37+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
38+ throw "produced artifact is not a PE (no MZ magic)"
39+ }
40+
41+ Write-Host ("Built plugin_tetris_3d.exe {0} bytes" -f $bytes.Length)
42+ & $Out --meta
43+ if ($LASTEXITCODE -ne 0) { throw "--meta smoke test failed" }
44+}
45+finally {
46+ Pop-Location
47+}
plugin.json+12−0■■■■■
11new file mode 100644
index 0000000..5742df5
--- /dev/null
+++ b/plugin.json
@@ -0,0 +1,12 @@
1+{
2+ "slug": "tetris-3d",
3+ "id": "plugin_tetris_3d",
4+ "title": "3D Block Puzzle Game",
5+ "summary": "Zero-dependency isometric 3D block-stacking puzzle that runs in the ScorpioX Bot Chat floating window or a standalone browser tab. Software-projected cubes on a canvas with ghost piece, next-piece preview, hold queue, keyboard and touch controls, dark and light themes, and local high-score persistence through the node plugin API. No WebGL, no CDN, no network requests.",
6+ "category": "utilities",
7+ "license": "MIT",
8+ "capabilities": ["local_filesystem_write"],
9+ "trust_notice": "Executes native C code on your node. Writes one small JSON file holding your local high scores inside the node plugin directory; it makes zero network requests and reads nothing else.",
10+ "author": "SCORPIOX INC",
11+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-tetris-3d"
12+}
release-dist.sh+364−0■■■■■
11new file mode 100755
index 0000000..c7883bf
--- /dev/null
+++ b/release-dist.sh
@@ -0,0 +1,364 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_tetris_3d to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI.
7+# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz ->
8+# manifest.json + SHA256SUMS -> upload -> latest.json / index.json.
9+#
10+# Nothing here contains a host address or a credential. Everything environment-specific
11+# comes from the environment, so this file stays safe to publish:
12+#
13+# DIST_HOST ssh target for the dist server (required for upload)
14+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
15+# DIST_PATH remote web root of the dist server (default /data/dist)
16+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
17+# MAC_USER / MAC_PASS (optional)
18+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
19+# PLUGINGIT_REMOTE public mirror URL to push into
20+#
21+# Usage:
22+# ./release-dist.sh # full release
23+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
24+# ./release-dist.sh --no-macos # skip the macOS legs
25+# ./release-dist.sh --no-mirror # skip the plugingit mirror
26+# ./release-dist.sh --standalone # use this script even if the CLI is installed
27+# # (needed for plugins that link extra Win32 libs,
28+# # which the CLI's fixed link line cannot express)
29+
30+set -euo pipefail
31+
32+SLUG="tetris-3d"
33+ID="plugin_tetris_3d"
34+VERSION="1.0.0"
35+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
36+
37+ROOT="$(cd "$(dirname "$0")" && pwd)"
38+cd "$ROOT"
39+
40+DRY_RUN=0
41+DO_MACOS=1
42+DO_MIRROR=1
43+STANDALONE=0
44+for arg in "$@"; do
45+ case "$arg" in
46+ --standalone) STANDALONE=1 ;;
47+ --dry-run) DRY_RUN=1 ;;
48+ --no-macos) DO_MACOS=0 ;;
49+ --no-mirror) DO_MIRROR=0 ;;
50+ -h|--help) sed -n '2,32p' "$0"; exit 0 ;;
51+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
52+ esac
53+done
54+
55+DIST_HOST="${DIST_HOST:-}"
56+DIST_PASS="${DIST_PASS:-}"
57+DIST_PATH="${DIST_PATH:-/data/dist}"
58+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
59+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
60+
61+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
62+mkdir -p "$STAGE"
63+trap 'rm -rf "$STAGE"' EXIT
64+
65+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
66+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
67+
68+# ---------------------------------------------------------------- 0. preflight
69+say "0/7 preflight"
70+
71+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
72+ say "using scorpiox-cli-botplugin publish"
73+ exec scorpiox-cli-botplugin publish "$ROOT"
74+fi
75+echo " running the standalone pipeline"
76+
77+[ -n "$(git status --porcelain 2>/dev/null)" ] && \
78+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
79+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
80+echo " version $VERSION"
81+echo " commit $COMMIT"
82+
83+# ---------------------------------------------------------------- 1. secret scan
84+say "1/7 secret & LAN scan (full history)"
85+
86+SCAN_TMP="$STAGE/history.txt"
87+# Scan every added/removed line of every commit. Two exclusions, both about the
88+# audit rather than the code: the committer identity line, and any line that is
89+# itself a scan definition - otherwise this file's own detector patterns read as
90+# findings in every historical revision of it.
91+git log -p --all 2>/dev/null \
92+ | grep -v '^Author: ' \
93+ | grep -vE 'scan "|audit "|HITS=|grep -E|P_ROOT=|P_WT=|PK="|\$ALL' \
94+ > "$SCAN_TMP" || : > "$SCAN_TMP"
95+HITS=0
96+scan() { # scan <label> <regex>
97+ local out
98+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
99+ if [ -n "$out" ]; then
100+ printf ' \033[31mHIT\033[0m %s\n' "$1"
101+ printf '%s\n' "$out" | sed 's/^/ /'
102+ HITS=$((HITS + 1))
103+ else
104+ printf ' ok %s\n' "$1"
105+ fi
106+}
107+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
108+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
109+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
110+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
111+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
112+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
113+scan "hard-coded ssh password" 'sshpass -p [^"$]'
114+P_ROOT="/codebases"
115+P_PICOBOT="${P_ROOT}/pico""bot"
116+P_WT=".work""trees"
117+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
118+scan "run-token env assignment" 'RUNNER_'"PASS="
119+if [ "$HITS" -ne 0 ]; then
120+ die "secret scan found $HITS problem(s) - refusing to publish"
121+fi
122+echo " clean: 0 hits"
123+
124+# ---------------------------------------------------------------- 2. build
125+say "2/7 build targets"
126+
127+# linux-x86_64 (glibc, native)
128+if command -v cc >/dev/null 2>&1; then
129+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed"
130+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
131+else
132+ die "no native cc found"
133+fi
134+
135+# linux-x86_64-musl (fully static - the universal Linux artifact)
136+if command -v musl-gcc >/dev/null 2>&1; then
137+ musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c \
138+ || die "musl build failed"
139+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
140+else
141+ echo " skip linux-x86_64-musl (no musl-gcc)"
142+fi
143+
144+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers)
145+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
146+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c \
147+ || die "arm64 build failed"
148+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
149+else
150+ echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)"
151+fi
152+
153+# windows-x86_64 (static PE)
154+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
155+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \
156+ -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed"
157+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
158+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
159+else
160+ echo " skip windows-x86_64 (no MinGW cross compiler)"
161+fi
162+
163+# macOS legs - Mach-O must be produced by Apple clang on a real Mac.
164+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
165+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
166+ MAC_USER="${MAC_USER:-$(whoami)}"
167+ MAC_DIR="/tmp/${ID}-mac-$$"
168+ echo " building macOS legs on $MAC_HOST"
169+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
170+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
171+ if [ -n "${MAC_PASS:-}" ]; then
172+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
173+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
174+ fi
175+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
176+ tar -czf "$STAGE/src.tgz" src
177+ if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \
178+ && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then
179+ # Build straight from the uploaded file - no src/ tree on the remote.
180+ for slice in arm64 x86_64; do
181+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
182+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c" \
183+ 2>/dev/null; then
184+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
185+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
186+ else
187+ echo " warn: macos-$slice build failed on $MAC_HOST"
188+ fi
189+ done
190+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true
191+ else
192+ echo " warn: could not upload source to $MAC_HOST"
193+ fi
194+ else
195+ echo " warn: cannot reach macOS builder $MAC_HOST"
196+ fi
197+else
198+ echo " skip macOS legs (no MAC_HOST or --no-macos)"
199+fi
200+
201+# ---------------------------------------------------------------- 3. manifest
202+say "3/7 manifest + checksums"
203+
204+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
205+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
206+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
207+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
208+
209+target_meta() { # target_meta <key> <file> <format> <relpath>
210+ local key="$1" file="$2" fmt="$3" rel="$4"
211+ [ -f "$file" ] || return 0
212+ local sha size
213+ sha=$(sha256sum "$file" | awk '{print $1}')
214+ size=$(wc -c < "$file" | tr -d ' ')
215+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
216+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
217+}
218+
219+{
220+ printf '{\n'
221+ printf ' "slug": "%s",\n' "$SLUG"
222+ printf ' "id": "%s",\n' "$ID"
223+ printf ' "name": "tetris",\n'
224+ printf ' "desc": "3D block game",\n'
225+ printf ' "title": "3D Block Puzzle Game",\n'
226+ printf ' "summary": "Zero-dependency isometric 3D block-stacking puzzle that runs in the ScorpioX Bot Chat floating window or a standalone browser tab. Software-projected cubes on a canvas with ghost piece, next-piece preview, hold queue, keyboard and touch controls, dark and light themes, and local high-score persistence through the node plugin API. No WebGL, no CDN, no network requests.",\n'
227+ printf ' "category": "utilities",\n'
228+ printf ' "version": "%s",\n' "$VERSION"
229+ printf ' "license": "MIT",\n'
230+ printf ' "trust_notice": "Executes native C code on your node. Writes one small JSON file holding your local high scores inside the node plugin directory; it makes zero network requests and reads nothing else.",\n'
231+ printf ' "capabilities": ["local_filesystem_write"],\n'
232+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
233+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
234+ printf ' "git_commit": "%s",\n' "$COMMIT"
235+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
236+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
237+ printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID"
238+ printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID"
239+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
240+ printf ' "targets": {\n'
241+ first=1
242+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
243+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
244+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
245+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
246+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
247+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
248+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
249+ printf '\n }\n}\n'
250+} > "$STAGE/manifest.json"
251+
252+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
253+ || die "generated manifest.json is not valid JSON"
254+echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)"
255+
256+# SHA256SUMS - relative paths, exactly as published
257+( cd "$STAGE"
258+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
259+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
260+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
261+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
262+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
263+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
264+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
265+ true ) > "$STAGE/SHA256SUMS"
266+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
267+
268+# ---------------------------------------------------------------- 4. stage
269+say "4/7 stage tree"
270+PKG="$STAGE/pkg"
271+mkdir -p "$PKG"
272+cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
273+[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; }
274+[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; }
275+[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; }
276+[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; }
277+[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; }
278+[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; }
279+echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)"
280+
281+if [ "$DRY_RUN" -eq 1 ]; then
282+ say "dry run - leaving the staging tree in $PKG"
283+ trap - EXIT
284+ exit 0
285+fi
286+
287+# ---------------------------------------------------------------- 5. upload
288+say "5/7 upload to the dist server"
289+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)"
290+SSH=(ssh -o StrictHostKeyChecking=no)
291+SCP=(scp -o StrictHostKeyChecking=no)
292+if [ -n "$DIST_PASS" ]; then
293+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
294+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
295+fi
296+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
297+
298+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
299+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
300+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
301+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
302+# OpenSSH 9 refuses to scp a bare "." source.
303+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
304+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
305+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
306+ || die "remote extract failed"
307+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
308+
309+# latest.json = copy of this version's manifest
310+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
311+ || die "latest.json update failed"
312+echo " updated bot-plugins/$SLUG/latest.json"
313+
314+# index.json - merge, preserving every sibling <slug>/latest.json
315+say "index.json merge"
316+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
317+import json, os, sys, glob
318+slug = sys.argv[1]
319+entries = {}
320+for p in sorted(glob.glob('*/latest.json')):
321+ s = os.path.dirname(p)
322+ try:
323+ entries[s] = json.load(open(p))
324+ except Exception:
325+ pass
326+index = {
327+ 'ok': True,
328+ 'service': 'bot-plugins-dist',
329+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
330+ 'count': len(entries),
331+ 'slugs': sorted(entries),
332+ 'plugins': [entries[k] for k in sorted(entries)],
333+}
334+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
335+os.replace('index.json.tmp', 'index.json')
336+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
337+PY" || die "index.json merge failed"
338+
339+# ---------------------------------------------------------------- 6. mirror
340+say "6/7 plugingit mirror"
341+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
342+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
343+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|")
344+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
345+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
346+ echo " mirrored to $PLUGINGIT_REMOTE"
347+else
348+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
349+fi
350+
351+# ---------------------------------------------------------------- 7. verify
352+say "7/7 verify"
353+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
354+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
355+if [ "$CODE" = "200" ]; then
356+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \
357+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
358+else
359+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
360+fi
361+
362+printf '\n\033[1mrelease complete\033[0m\n'
363+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
364+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/plugin_tetris_3d.c+458−0■■■■■
11new file mode 100644
index 0000000..00a217d
--- /dev/null
+++ b/src/plugin_tetris_3d.c
@@ -0,0 +1,458 @@
1+/*
2+ * plugin_tetris_3d - ScorpioX Bot open-source 3D block game (clean room)
3+ *
4+ * A single dependency-free C99 binary that serves THREE modes:
5+ * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
6+ * 2. ?action=scores | ?action=save_score | ?format=json -> JSON node API
7+ * 3. GET (default) -> self-contained HTML game UI
8+ *
9+ * The game itself is a 3D block-stacking puzzle rendered by a small software
10+ * 3D projector onto a 2D canvas. There is no WebGL requirement, no CDN, no
11+ * third-party JavaScript and no runtime library beyond libc, so the UI works
12+ * offline on every node and produces zero network requests.
13+ *
14+ * High scores are stored locally in a small JSON file inside the node plugin
15+ * directory:
16+ * POSIX ~/.scorpiox/plugins/.tetris_scores.json
17+ * ($BOT_PLUGIN_DIR when set, /workspace/.scorpiox/plugins on BotCloud)
18+ * Windows %LOCALAPPDATA%\scorpiox\plugins\.tetris_scores.json
19+ * override SX_TETRIS_SCORES (full path, used by the test suite)
20+ *
21+ * Nothing else is read or written. There is no parameter anywhere in this
22+ * file that can point it at another host.
23+ *
24+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
25+ */
26+
27+#if defined(_WIN32) && !defined(_WIN32_WINNT)
28+# define _WIN32_WINNT 0x0601
29+#endif
30+
31+#if !defined(_WIN32)
32+# define _POSIX_C_SOURCE 200809L
33+# define _DEFAULT_SOURCE 1
34+# if defined(__APPLE__)
35+# define _DARWIN_C_SOURCE 1
36+# endif
37+#endif
38+
39+#include <stdio.h>
40+#include <stdlib.h>
41+#include <string.h>
42+#include <ctype.h>
43+#include <time.h>
44+#include <errno.h>
45+
46+#if defined(_WIN32)
47+# define WIN32_LEAN_AND_MEAN
48+# include <windows.h>
49+# include <direct.h>
50+# define SX_SEP '\\'
51+#else
52+# include <unistd.h>
53+# include <sys/stat.h>
54+# include <sys/types.h>
55+# define SX_SEP '/'
56+#endif
57+
58+#define PLUGIN_SLUG "tetris-3d"
59+#define PLUGIN_ID "plugin_tetris_3d"
60+#define PLUGIN_NAME "tetris"
61+#define PLUGIN_DESC "3D block game"
62+#define PLUGIN_VER "1.0.0"
63+
64+#define MAX_SCORES 10
65+#define PATH_SZ 1024
66+#define BODY_SZ 2048
67+
68+/* ------------------------------------------------------------------ */
69+/* Small string helpers */
70+/* ------------------------------------------------------------------ */
71+
72+static void str_copy(char *dst, size_t sz, const char *src)
73+{
74+ size_t i = 0;
75+ if (!dst || sz == 0) return;
76+ if (!src) { dst[0] = '\0'; return; }
77+ while (i + 1 < sz && src[i]) { dst[i] = src[i]; i++; }
78+ dst[i] = '\0';
79+}
80+
81+static void url_decode(char *s)
82+{
83+ char *o = s;
84+ if (!s) return;
85+ while (*s) {
86+ if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
87+ int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
88+ int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
89+ *o++ = (char)((hi << 4) | lo);
90+ s += 3;
91+ } else if (*s == '+') {
92+ *o++ = ' ';
93+ s++;
94+ } else {
95+ *o++ = *s++;
96+ }
97+ }
98+ *o = '\0';
99+}
100+
101+/* Read one query/body parameter, percent-decoded. Returns 1 when present. */
102+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
103+{
104+ size_t klen;
105+ const char *p;
106+
107+ if (!out || outsz == 0) return 0;
108+ out[0] = '\0';
109+ if (!qs || !key) return 0;
110+ klen = strlen(key);
111+
112+ for (p = qs; *p; ) {
113+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
114+ const char *v = p + klen + 1;
115+ size_t i = 0;
116+ while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++;
117+ out[i] = '\0';
118+ url_decode(out);
119+ return 1;
120+ }
121+ p = strchr(p, '&');
122+ if (!p) break;
123+ p++;
124+ }
125+ return 0;
126+}
127+
128+/* ------------------------------------------------------------------ */
129+/* Node security */
130+/* ------------------------------------------------------------------ */
131+
132+/* Accept X-Bot-Password, Authorization: Bearer <pwd> or ?pwd=. The bot web
133+ * frontend appends ?pwd= for iframes, so all three forms must work. When
134+ * BOT_PASSWORD is unset the node is unauthenticated by configuration and the
135+ * check is a no-op. --meta stays unauthenticated so discovery works. */
136+static void require_node_auth(void)
137+{
138+ const char *np = getenv("BOT_PASSWORD");
139+ const char *xp;
140+ const char *auth;
141+
142+ if (!np || !*np) return;
143+
144+ xp = getenv("HTTP_X_BOT_PASSWORD");
145+ if (xp && strcmp(xp, np) == 0) return;
146+
147+ auth = getenv("HTTP_AUTHORIZATION");
148+ if (auth) {
149+ while (*auth == ' ') auth++;
150+ if (strncmp(auth, "Bearer ", 7) == 0) {
151+ auth += 7;
152+ while (*auth == ' ') auth++;
153+ if (strcmp(auth, np) == 0) return;
154+ }
155+ }
156+
157+ {
158+ char qpwd[256];
159+ const char *qs = getenv("QUERY_STRING");
160+ if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) return;
161+ }
162+
163+ fputs("Status: 401 Unauthorized\r\n"
164+ "Content-Type: application/json; charset=utf-8\r\n"
165+ "Cache-Control: no-store\r\n\r\n"
166+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
167+ exit(0);
168+}
169+
170+/* ------------------------------------------------------------------ */
171+/* Local high-score store */
172+/* ------------------------------------------------------------------ */
173+
174+typedef struct {
175+ long v[MAX_SCORES];
176+ int n;
177+} Scores;
178+
179+static void path_join(char *dst, size_t sz, const char *a, const char *b)
180+{
181+ if (!dst || sz == 0) return;
182+ dst[0] = '\0';
183+ if (!a || !b) return;
184+ if (!*a) { str_copy(dst, sz, b); return; }
185+ str_copy(dst, sz, a);
186+ {
187+ size_t l = strlen(dst);
188+ if (l + 1 < sz) { dst[l] = SX_SEP; dst[l + 1] = '\0'; }
189+ }
190+ {
191+ size_t l = strlen(dst);
192+ size_t i = 0;
193+ while (l + i + 1 < sz && b[i]) { dst[l + i] = b[i]; i++; }
194+ dst[l + i] = '\0';
195+ }
196+}
197+
198+static void mkdir_one(const char *p)
199+{
200+#if defined(_WIN32)
201+ _mkdir(p);
202+#else
203+ mkdir(p, 0700);
204+#endif
205+}
206+
207+/* Resolve <plugin dir>/.tetris_scores.json */
208+static int scores_path(char *out, size_t sz)
209+{
210+ const char *env = getenv("SX_TETRIS_SCORES");
211+ char dir[PATH_SZ];
212+ const char *base;
213+
214+ if (env && *env) { str_copy(out, sz, env); return 1; }
215+
216+ base = getenv("BOT_PLUGIN_DIR");
217+ if (base && *base) {
218+ mkdir_one(base);
219+ dir[0] = '\0';
220+ str_copy(dir, sizeof dir, base);
221+ } else {
222+#if defined(_WIN32)
223+ const char *la = getenv("LOCALAPPDATA");
224+ if (la && *la) {
225+ path_join(dir, sizeof dir, la, "scorpiox");
226+ } else {
227+ const char *up = getenv("USERPROFILE");
228+ if (up && *up) {
229+ path_join(dir, sizeof dir, up, ".scorpiox");
230+ } else {
231+ str_copy(dir, sizeof dir, ".");
232+ }
233+ }
234+ mkdir_one(dir);
235+ {
236+ char tmp[PATH_SZ];
237+ path_join(tmp, sizeof tmp, dir, "plugins");
238+ str_copy(dir, sizeof dir, tmp);
239+ mkdir_one(dir);
240+ }
241+#else
242+ const char *home = getenv("HOME");
243+# if defined(__APPLE__)
244+ if (access("/workspace", W_OK) == 0) {
245+ path_join(dir, sizeof dir, "/workspace/.scorpiox", "plugins");
246+ } else
247+# endif
248+ if (home && *home) {
249+ path_join(dir, sizeof dir, home, ".scorpiox");
250+ mkdir_one(dir);
251+ {
252+ char tmp[PATH_SZ];
253+ path_join(tmp, sizeof tmp, dir, "plugins");
254+ str_copy(dir, sizeof dir, tmp);
255+ }
256+ mkdir_one(dir);
257+ } else {
258+ str_copy(dir, sizeof dir, ".");
259+ }
260+#endif
261+ }
262+ path_join(out, sz, dir, ".tetris_scores.json");
263+ return 1;
264+}
265+
266+static void scores_load(Scores *s)
267+{
268+ char path[PATH_SZ];
269+ FILE *fp;
270+ char buf[BODY_SZ];
271+ size_t got;
272+
273+ memset(s, 0, sizeof *s);
274+ if (!scores_path(path, sizeof path)) return;
275+
276+ fp = fopen(path, "rb");
277+ if (!fp) return;
278+ got = fread(buf, 1, sizeof buf - 1, fp);
279+ fclose(fp);
280+ buf[got] = '\0';
281+
282+ {
283+ const char *p = strstr(buf, "\"scores\"");
284+ if (!p) p = buf;
285+ p = strchr(p, '[');
286+ if (!p) return;
287+ p++;
288+ while (*p && s->n < MAX_SCORES) {
289+ while (*p && !isdigit((unsigned char)*p) && *p != ']') p++;
290+ if (!*p || *p == ']') break;
291+ {
292+ long v = strtol(p, NULL, 10);
293+ if (v > 0) s->v[s->n++] = v;
294+ while (*p && *p != ',' && *p != ']') p++;
295+ if (*p == ',') p++;
296+ }
297+ }
298+ }
299+}
300+
301+static int scores_save(const Scores *s)
302+{
303+ char path[PATH_SZ];
304+ FILE *fp;
305+ int i;
306+
307+ if (!scores_path(path, sizeof path)) return 0;
308+ fp = fopen(path, "wb");
309+ if (!fp) return 0;
310+ fputs("{\"scores\":[", fp);
311+ for (i = 0; i < s->n; i++) {
312+ if (i) fputc(',', fp);
313+ fprintf(fp, "%ld", s->v[i]);
314+ }
315+ fputs("]}\n", fp);
316+ fclose(fp);
317+ return 1;
318+}
319+
320+static void scores_add(Scores *s, long val)
321+{
322+ int i, pos;
323+ if (val <= 0) return;
324+ if (s->n < MAX_SCORES) {
325+ pos = s->n++;
326+ } else {
327+ if (val <= s->v[MAX_SCORES - 1]) return;
328+ pos = MAX_SCORES - 1;
329+ }
330+ for (i = pos; i > 0 && s->v[i - 1] < val; i--) s->v[i] = s->v[i - 1];
331+ s->v[i] = val;
332+}
333+
334+static void scores_print_json(const Scores *s)
335+{
336+ int i;
337+ printf("{\"ok\":true,\"plugin\":\"%s\",\"version\":\"%s\",\"highscore\":%ld,\"scores\":[",
338+ PLUGIN_ID, PLUGIN_VER, s->n ? s->v[0] : 0L);
339+ for (i = 0; i < s->n; i++) {
340+ if (i) fputc(',', stdout);
341+ printf("%ld", s->v[i]);
342+ }
343+ fputs("]}\n", stdout);
344+}
345+
346+/* Read the POST body when the frontend actually sent one. Guarded on
347+ * CONTENT_LENGTH so an inherited empty stdin never blocks the process. */
348+static int read_body(char *out, size_t sz)
349+{
350+ const char *cl = getenv("CONTENT_LENGTH");
351+ long len;
352+ size_t got;
353+
354+ if (!out || sz == 0) return 0;
355+ out[0] = '\0';
356+ if (!cl || !*cl) return 0;
357+ len = strtol(cl, NULL, 10);
358+ if (len <= 0) return 0;
359+ if ((size_t)len > sz - 1) len = (long)sz - 1;
360+ got = fread(out, 1, (size_t)len, stdin);
361+ out[got] = '\0';
362+ return (int)got;
363+}
364+
365+/* ------------------------------------------------------------------ */
366+/* Modes */
367+/* ------------------------------------------------------------------ */
368+
369+#include "ui_html.h"
370+
371+static const char *method(void)
372+{
373+ const char *m = getenv("REQUEST_METHOD");
374+ return (m && *m) ? m : "GET";
375+}
376+
377+int main(int argc, char **argv)
378+{
379+ const char *qs;
380+ char action[64];
381+ char valstr[64];
382+ char body[BODY_SZ];
383+ Scores scores;
384+
385+ /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */
386+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
387+ printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC);
388+ return 0;
389+ }
390+ if (argc > 1 && strcmp(argv[1], "--version") == 0) {
391+ printf("%s %s\n", PLUGIN_ID, PLUGIN_VER);
392+ return 0;
393+ }
394+
395+ require_node_auth();
396+ qs = getenv("QUERY_STRING");
397+ if (!qs) qs = "";
398+
399+ action[0] = '\0';
400+ valstr[0] = '\0';
401+ get_query_val(qs, "action", action, sizeof action);
402+
403+ /* 2. JSON API: ?action=..., ?format=json, or any POST with a body */
404+ if (action[0] || strstr(qs, "format=json") || strncmp(method(), "POST", 4) == 0) {
405+ char format[32];
406+ format[0] = '\0';
407+ get_query_val(qs, "format", format, sizeof format);
408+
409+ if (!action[0] && strncmp(method(), "POST", 4) == 0) str_copy(action, sizeof action, "save_score");
410+ if (!action[0]) str_copy(action, sizeof action, "scores");
411+
412+ read_body(body, sizeof body);
413+ if (!get_query_val(qs, "val", valstr, sizeof valstr) && body[0]) {
414+ if (!get_query_val(body, "val", valstr, sizeof valstr))
415+ (void)get_query_val(body, "score", valstr, sizeof valstr);
416+ }
417+ if (!valstr[0]) get_query_val(qs, "score", valstr, sizeof valstr);
418+ if (!valstr[0] && body[0]) {
419+ /* a bare numeric body is accepted too */
420+ const char *p = body;
421+ while (*p && !isdigit((unsigned char)*p) && *p != '-') p++;
422+ if (*p) str_copy(valstr, sizeof valstr, p);
423+ }
424+
425+ scores_load(&scores);
426+
427+ fputs("Content-Type: application/json; charset=utf-8\r\n"
428+ "Cache-Control: no-store\r\n\r\n", stdout);
429+
430+ if (strcmp(action, "save_score") == 0) {
431+ long v = strtol(valstr, NULL, 10);
432+ if (v > 0) {
433+ scores_add(&scores, v);
434+ if (!scores_save(&scores))
435+ printf("{\"ok\":false,\"error\":\"score_store_unwritable\",\"highscore\":%ld}\n",
436+ scores.n ? scores.v[0] : 0L);
437+ else
438+ scores_print_json(&scores);
439+ } else {
440+ printf("{\"ok\":false,\"error\":\"invalid_score\"}\n");
441+ }
442+ return 0;
443+ }
444+ if (strcmp(action, "scores") == 0 || strcmp(action, "highscore") == 0 ||
445+ strcmp(action, "leaderboard") == 0) {
446+ scores_print_json(&scores);
447+ return 0;
448+ }
449+ printf("{\"ok\":false,\"error\":\"unknown_action\"}\n");
450+ return 0;
451+ }
452+
453+ /* 3. HTML UI */
454+ fputs("Content-Type: text/html; charset=utf-8\r\n"
455+ "Cache-Control: no-store\r\n\r\n", stdout);
456+ fputs(UI_HTML, stdout);
457+ return 0;
458+}
src/ui_html.h+583−0■■■■■
11new file mode 100644
index 0000000..0646853
--- /dev/null
+++ b/src/ui_html.h
@@ -0,0 +1,583 @@
1+/* Generated from the single-file UI template. Do not edit by hand. */
2+#ifndef SX_TETRIS_UI_HTML_H
3+#define SX_TETRIS_UI_HTML_H
4+
5+static const char *UI_HTML =
6+ "<!DOCTYPE html>\n"
7+ "<html lang=\"en\"><head><meta charset=\"utf-8\">\n"
8+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no\">\n"
9+ "<title>tetris</title>\n"
10+ "<style>\n"
11+ ":root{color-scheme:dark light;--bg:#08080b;--panel:rgba(22,22,28,.72);--panel-solid:#16161c;--text:#f4f4f7;--muted:#9b9ba6;--line:rgba(255,255,255,.11);--accent:#0a84ff;--good:#30d158;--warn:#ff9f0a;--radius:14px}\n"
12+ "@media(prefers-color-scheme:light){:root{--bg:#eceef3;--panel:rgba(255,255,255,.78);--panel-solid:#fff;--text:#14141a;--muted:#5f5f6b;--line:rgba(0,0,0,.1)}}\n"
13+ "html[data-theme=\"dark\"]{--bg:#08080b;--panel:rgba(22,22,28,.72);--panel-solid:#16161c;--text:#f4f4f7;--muted:#9b9ba6;--line:rgba(255,255,255,.11)}\n"
14+ "html[data-theme=\"light\"]{--bg:#eceef3;--panel:rgba(255,255,255,.78);--panel-solid:#fff;--text:#14141a;--muted:#5f5f6b;--line:rgba(0,0,0,.1)}\n"
15+ "*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}\n"
16+ "html,body{margin:0;padding:0;height:100%;overflow:hidden;background:var(--bg);color:var(--text);font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Inter,system-ui,sans-serif}\n"
17+ "#app{position:relative;width:100%;height:100%;display:flex;flex-direction:column}\n"
18+ "#top{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:8px 10px;flex:0 0 auto;z-index:5}\n"
19+ "#title{display:flex;align-items:center;gap:8px;font-size:12px;font-weight:700;letter-spacing:.9px;text-transform:uppercase;color:var(--muted)}\n"
20+ "#dot{width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 10px var(--accent)}\n"
21+ "#topbtns{display:flex;gap:6px}\n"
22+ ".iconbtn{background:var(--panel);border:1px solid var(--line);color:var(--text);border-radius:10px;padding:6px 10px;font-size:11px;font-weight:650;cursor:pointer;backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);font-family:inherit}\n"
23+ ".iconbtn:active{transform:scale(.95)}\n"
24+ "#main{flex:1 1 auto;display:flex;gap:10px;padding:0 10px 10px;min-height:0}\n"
25+ "#stage{position:relative;flex:1 1 auto;min-width:0;border-radius:var(--radius);overflow:hidden;background:radial-gradient(120% 90% at 50% 0%,rgba(10,132,255,.10),transparent 60%),var(--panel);border:1px solid var(--line);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px)}\n"
26+ "#cv{display:block;width:100%;height:100%;touch-action:none}\n"
27+ "#side{flex:0 0 132px;display:flex;flex-direction:column;gap:8px;overflow:hidden}\n"
28+ ".card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:8px 10px;backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px)}\n"
29+ ".lbl{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--muted);font-weight:700}\n"
30+ ".val{font-variant-numeric:tabular-nums;font-size:19px;font-weight:750;line-height:1.15}\n"
31+ ".val.sm{font-size:12px;font-weight:650}\n"
32+ ".mini{width:100%;height:66px;display:block}\n"
33+ ".mini.tall{height:150px}\n"
34+ "#overlay{position:absolute;inset:0;display:none;align-items:center;justify-content:center;background:rgba(6,6,9,.78);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);z-index:20;padding:16px}\n"
35+ "#overlay.on{display:flex}\n"
36+ "#modal{background:var(--panel-solid);border:1px solid var(--line);border-radius:18px;padding:20px 22px;text-align:center;max-width:300px;width:100%}\n"
37+ "#mTitle{margin:0 0 6px;font-size:20px;font-weight:800;letter-spacing:1.4px}\n"
38+ "#mSub{margin:0 0 14px;font-size:12px;color:var(--muted);line-height:1.5}\n"
39+ "#mBtn{background:var(--accent);color:#fff;border:0;border-radius:999px;padding:11px 26px;font-size:14px;font-weight:750;cursor:pointer;font-family:inherit;width:100%}\n"
40+ "#mBtn:active{transform:scale(.97)}\n"
41+ "#pad{flex:0 0 auto;display:grid;grid-template-columns:repeat(4,1fr);gap:6px;padding:0 10px 10px}\n"
42+ ".pbtn{background:var(--panel);border:1px solid var(--line);color:var(--text);border-radius:12px;padding:12px 0;font-size:15px;font-weight:700;cursor:pointer;font-family:inherit;backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);user-select:none;touch-action:manipulation}\n"
43+ ".pbtn:active{background:var(--accent);color:#fff;transform:scale(.95)}\n"
44+ ".pbtn.wide{grid-column:span 2}\n"
45+ ".pbtn.hi{background:rgba(10,132,255,.18);border-color:rgba(10,132,255,.45);color:#5db0ff}\n"
46+ "html[data-theme=\"light\"] .pbtn.hi{color:#0071e3}\n"
47+ "@media(prefers-color-scheme:light){html:not([data-theme=\"dark\"]) .pbtn.hi{color:#0071e3;background:rgba(0,113,227,.14);border-color:rgba(0,113,227,.42)}}\n"
48+ "@media (max-width:420px){\n"
49+ " #side{flex:0 0 92px}\n"
50+ " .val{font-size:15px}\n"
51+ " .mini{height:52px}\n"
52+ " .mini.tall{height:110px}\n"
53+ " #pad{gap:5px;padding:0 8px 8px}\n"
54+ " .pbtn{padding:10px 0;font-size:14px}\n"
55+ " #main{gap:7px;padding:0 8px 8px}\n"
56+ " #top{padding:7px 8px}\n"
57+ "}\n"
58+ "@media (max-height:560px){\n"
59+ " .mini{height:44px}\n"
60+ " .mini.tall{height:84px}\n"
61+ " #pad{padding-bottom:6px}\n"
62+ " .pbtn{padding:8px 0}\n"
63+ "}\n"
64+ "</style></head>\n"
65+ "<body><div id=\"app\">\n"
66+ "<div id=\"top\">\n"
67+ " <div id=\"title\"><span id=\"dot\"></span><span>3D BLOCKS</span></div>\n"
68+ " <div id=\"topbtns\">\n"
69+ " <button class=\"iconbtn\" id=\"btnTheme\" type=\"button\">Theme</button>\n"
70+ " <button class=\"iconbtn\" id=\"btnRestart\" type=\"button\">Restart</button>\n"
71+ " </div>\n"
72+ "</div>\n"
73+ "<div id=\"main\">\n"
74+ " <div id=\"stage\"><canvas id=\"cv\"></canvas>\n"
75+ " <div id=\"overlay\"><div id=\"modal\">\n"
76+ " <h2 id=\"mTitle\">READY</h2>\n"
77+ " <p id=\"mSub\">Arrows or WASD to move and rotate. Space drops.</p>\n"
78+ " <button id=\"mBtn\" type=\"button\">Start</button>\n"
79+ " </div></div>\n"
80+ " </div>\n"
81+ " <div id=\"side\">\n"
82+ " <div class=\"card\"><div class=\"lbl\">Score</div><div class=\"val\" id=\"vScore\">0</div></div>\n"
83+ " <div class=\"card\"><div class=\"lbl\">Best</div><div class=\"val\" id=\"vBest\">0</div></div>\n"
84+ " <div class=\"card\"><div class=\"lbl\">Lines / Level</div><div class=\"val sm\" id=\"vLines\">0 / 1</div></div>\n"
85+ " <div class=\"card\"><div class=\"lbl\">Next</div><canvas class=\"mini tall\" id=\"cvNext\"></canvas></div>\n"
86+ " <div class=\"card\"><div class=\"lbl\">Hold</div><canvas class=\"mini\" id=\"cvHold\"></canvas></div>\n"
87+ " </div>\n"
88+ "</div>\n"
89+ "<div id=\"pad\">\n"
90+ " <button class=\"pbtn\" id=\"bLeft\" type=\"button\">Left</button>\n"
91+ " <button class=\"pbtn\" id=\"bRot\" type=\"button\">Rotate</button>\n"
92+ " <button class=\"pbtn\" id=\"bRight\" type=\"button\">Right</button>\n"
93+ " <button class=\"pbtn\" id=\"bDown\" type=\"button\">Down</button>\n"
94+ " <button class=\"pbtn wide hi\" id=\"bDrop\" type=\"button\">Hard Drop</button>\n"
95+ " <button class=\"pbtn\" id=\"bHold\" type=\"button\">Hold</button>\n"
96+ " <button class=\"pbtn\" id=\"bPause\" type=\"button\">Pause</button>\n"
97+ "</div>\n"
98+ "</div>\n"
99+ "<script>\n"
100+ "(function(){\n"
101+ "\"use strict\";\n"
102+ "\n"
103+ "var q = new URLSearchParams(location.search);\n"
104+ "var HUB = q.get('plugin') || '';\n"
105+ "var NODE = q.get('node') || '';\n"
106+ "var SID = q.get('id') || '';\n"
107+ "var PWD = q.get('pwd') || (NODE ? (localStorage.getItem('bot_pwd_' + NODE) || '') : (localStorage.getItem('bot_active_pwd') || ''));\n"
108+ "var EMBED = q.get('embed') === '1' || q.get('embed') === 'true';\n"
109+ "\n"
110+ "/* The hub proxies through /plugins?plugin=<id>; a node opened directly serves\n"
111+ " the plugin itself at /plugin_tetris_3d. Calling /plugins?plugin= on a node\n"
112+ " returns the discovery list, not the plugin, so branch on which one we are. */\n"
113+ "function apiUrl(action, extra){\n"
114+ " var base = HUB ? ('/plugins?plugin=' + encodeURIComponent(HUB) + '&action=' + encodeURIComponent(action))\n"
115+ " : ('/plugin_tetris_3d?action=' + encodeURIComponent(action));\n"
116+ " if (extra) base += '&' + extra;\n"
117+ " if (NODE) base += '&node=' + encodeURIComponent(NODE);\n"
118+ " if (SID) base += '&id=' + encodeURIComponent(SID);\n"
119+ " if (PWD) base += '&pwd=' + encodeURIComponent(PWD);\n"
120+ " return base;\n"
121+ "}\n"
122+ "function api(action, extra, opts){\n"
123+ " var o = opts || {};\n"
124+ " if (PWD) o.headers = Object.assign({'X-Bot-Password': PWD}, o.headers || {});\n"
125+ " return fetch(apiUrl(action, extra), o).then(function(r){ return r.json(); });\n"
126+ "}\n"
127+ "\n"
128+ "/* ---------------------------------------------------------------- theme */\n"
129+ "var THEME_KEY = 'sx_tetris_theme';\n"
130+ "function applyTheme(t){\n"
131+ " if (t === 'dark' || t === 'light') document.documentElement.setAttribute('data-theme', t);\n"
132+ " else document.documentElement.removeAttribute('data-theme');\n"
133+ " document.getElementById('btnTheme').textContent =\n"
134+ " (document.documentElement.getAttribute('data-theme') === 'light') ? 'Dark' : 'Light';\n"
135+ "}\n"
136+ "applyTheme(localStorage.getItem(THEME_KEY) || q.get('theme') || '');\n"
137+ "document.getElementById('btnTheme').addEventListener('click', function(){\n"
138+ " var cur = document.documentElement.getAttribute('data-theme');\n"
139+ " if (!cur) cur = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';\n"
140+ " var next = cur === 'light' ? 'dark' : 'light';\n"
141+ " localStorage.setItem(THEME_KEY, next);\n"
142+ " applyTheme(next);\n"
143+ "});\n"
144+ "\n"
145+ "/* ---------------------------------------------------------------- board */\n"
146+ "var COLS = 10, ROWS = 20, DEPTH = 3;\n"
147+ "var SHAPES = [\n"
148+ " { k:'I', c:'#22d3ee', b:[[1,1,1,1]] },\n"
149+ " { k:'J', c:'#3b82f6', b:[[1,0,0],[1,1,1]] },\n"
150+ " { k:'L', c:'#f59e0b', b:[[0,0,1],[1,1,1]] },\n"
151+ " { k:'O', c:'#facc15', b:[[1,1],[1,1]] },\n"
152+ " { k:'S', c:'#22c55e', b:[[0,1,1],[1,1,0]] },\n"
153+ " { k:'T', c:'#a855f7', b:[[0,1,0],[1,1,1]] },\n"
154+ " { k:'Z', c:'#ef4444', b:[[1,1,0],[0,1,1]] }\n"
155+ "];\n"
156+ "\n"
157+ "var grid = []; /* grid[y][x] = color string or 0 */\n"
158+ "var piece = null; /* {c, b, x, y} */\n"
159+ "var nextQueue = [];\n"
160+ "var holdColor = null, holdUsed = false;\n"
161+ "var score = 0, lines = 0, level = 1, best = 0;\n"
162+ "var paused = false, over = false, started = false;\n"
163+ "var dropAcc = 0, dropInterval = 800, lastTs = 0;\n"
164+ "var flash = []; /* {rows:[], t:0} */\n"
165+ "\n"
166+ "for (var gy = 0; gy < ROWS; gy++) { grid[gy] = []; for (var gx = 0; gx < COLS; gx++) grid[gy][gx] = 0; }\n"
167+ "\n"
168+ "function newBag(){\n"
169+ " var bag = SHAPES.slice();\n"
170+ " for (var i = bag.length - 1; i > 0; i--) {\n"
171+ " var j = Math.floor(Math.random() * (i + 1));\n"
172+ " var t = bag[i]; bag[i] = bag[j]; bag[j] = t;\n"
173+ " }\n"
174+ " return bag;\n"
175+ "}\n"
176+ "function refill(){\n"
177+ " while (nextQueue.length < 5) nextQueue = nextQueue.concat(newBag());\n"
178+ "}\n"
179+ "function nextPiece(){\n"
180+ " refill();\n"
181+ " var s = nextQueue.shift();\n"
182+ " refill();\n"
183+ " return s;\n"
184+ "}\n"
185+ "function spawn(){\n"
186+ " var s = nextPiece();\n"
187+ " piece = { c: s.c, b: s.b.map(function(r){ return r.slice(); }),\n"
188+ " x: Math.floor((COLS - s.b[0].length) / 2), y: ROWS - s.b.length };\n"
189+ " holdUsed = false;\n"
190+ " if (collides(piece.x, piece.y, piece.b)) { gameOver(); }\n"
191+ " drawSide();\n"
192+ "}\n"
193+ "\n"
194+ "function collides(px, py, b){\n"
195+ " for (var r = 0; r < b.length; r++) {\n"
196+ " for (var c = 0; c < b[r].length; c++) {\n"
197+ " if (!b[r][c]) continue;\n"
198+ " var nx = px + c, ny = py + r;\n"
199+ " if (nx < 0 || nx >= COLS || ny < 0) return true;\n"
200+ " if (ny < ROWS && grid[ny][nx]) return true;\n"
201+ " }\n"
202+ " }\n"
203+ " return false;\n"
204+ "}\n"
205+ "function rotated(b, dir){\n"
206+ " var h = b.length, w = b[0].length, out = [], r, c;\n"
207+ " if (dir > 0) { for (c = 0; c < w; c++) { out[c] = []; for (r = h - 1; r >= 0; r--) out[c][h - 1 - r] = b[r][c]; } }\n"
208+ " else { for (c = 0; c < w; c++) { out[c] = []; for (r = 0; r < h; r++) out[c][r] = b[r][w - 1 - c]; } }\n"
209+ " return out;\n"
210+ "}\n"
211+ "function tryRotate(dir){\n"
212+ " if (!piece || paused || over) return;\n"
213+ " var nb = rotated(piece.b, dir);\n"
214+ " var kicks = [0, -1, 1, -2, 2];\n"
215+ " for (var i = 0; i < kicks.length; i++) {\n"
216+ " if (!collides(piece.x + kicks[i], piece.y, nb)) {\n"
217+ " piece.b = nb; piece.x += kicks[i]; return true;\n"
218+ " }\n"
219+ " }\n"
220+ " return false;\n"
221+ "}\n"
222+ "function move(dx){\n"
223+ " if (!piece || paused || over) return;\n"
224+ " if (!collides(piece.x + dx, piece.y, piece.b)) piece.x += dx;\n"
225+ "}\n"
226+ "function softDrop(){\n"
227+ " if (!piece || paused || over) return;\n"
228+ " if (!collides(piece.x, piece.y - 1, piece.b)) { piece.y -= 1; score += 1; dropAcc = 0; }\n"
229+ " else lock();\n"
230+ " updateHud();\n"
231+ "}\n"
232+ "function ghostY(){\n"
233+ " if (!piece) return 0;\n"
234+ " var y = piece.y;\n"
235+ " while (!collides(piece.x, y - 1, piece.b)) y--;\n"
236+ " return y;\n"
237+ "}\n"
238+ "function hardDrop(){\n"
239+ " if (!piece || paused || over) return;\n"
240+ " var gy2 = ghostY();\n"
241+ " score += Math.max(0, piece.y - gy2) * 2;\n"
242+ " piece.y = gy2;\n"
243+ " lock();\n"
244+ "}\n"
245+ "function lock(){\n"
246+ " var locked = false;\n"
247+ " for (var r = 0; r < piece.b.length; r++) {\n"
248+ " for (var c = 0; c < piece.b[r].length; c++) {\n"
249+ " if (!piece.b[r][c]) continue;\n"
250+ " var ny = piece.y + r, nx = piece.x + c;\n"
251+ " if (ny >= 0 && ny < ROWS && nx >= 0 && nx < COLS) { grid[ny][nx] = piece.c; locked = true; }\n"
252+ " }\n"
253+ " }\n"
254+ " piece = null;\n"
255+ " if (!locked) { gameOver(); return; }\n"
256+ " clearLines();\n"
257+ " if (!over) spawn();\n"
258+ " updateHud();\n"
259+ "}\n"
260+ "function clearLines(){\n"
261+ " var full = [];\n"
262+ " for (var y = 0; y < ROWS; y++) {\n"
263+ " var all = true;\n"
264+ " for (var x = 0; x < COLS; x++) if (!grid[y][x]) { all = false; break; }\n"
265+ " if (all) full.push(y);\n"
266+ " }\n"
267+ " if (!full.length) return;\n"
268+ " var table = [0, 100, 300, 500, 800];\n"
269+ " score += (table[full.length] || 1200) * level;\n"
270+ " lines += full.length;\n"
271+ " var newLevel = Math.floor(lines / 10) + 1;\n"
272+ " if (newLevel !== level) { level = newLevel; dropInterval = Math.max(90, 800 - (level - 1) * 62); }\n"
273+ " var kept = [];\n"
274+ " for (var y2 = 0; y2 < ROWS; y2++) if (full.indexOf(y2) < 0) kept.push(grid[y2]);\n"
275+ " while (kept.length < ROWS) { var row = []; for (var i = 0; i < COLS; i++) row[i] = 0; kept.push(row); }\n"
276+ " grid = kept;\n"
277+ " flash.push({ t: 1 });\n"
278+ "}\n"
279+ "function hold(){\n"
280+ " if (!piece || paused || over || holdUsed) return;\n"
281+ " var cur = { c: piece.c, b: piece.b };\n"
282+ " if (holdColor) {\n"
283+ " var hc = holdColor;\n"
284+ " piece = { c: hc.c, b: hc.b.map(function(r){ return r.slice(); }),\n"
285+ " x: Math.floor((COLS - hc.b[0].length) / 2), y: ROWS - hc.b.length };\n"
286+ " } else {\n"
287+ " spawn();\n"
288+ " }\n"
289+ " holdColor = cur;\n"
290+ " holdUsed = true;\n"
291+ " drawSide();\n"
292+ "}\n"
293+ "function gameOver(){\n"
294+ " over = true; paused = false; piece = null;\n"
295+ " if (score > best) { best = score; persist(); }\n"
296+ " updateHud();\n"
297+ " showModal('GAME OVER', 'Score ' + score + ' - ' + lines + ' lines. Best ' + best + '.', 'Play Again');\n"
298+ "}\n"
299+ "function persist(){\n"
300+ " var act = score > best ? 'save_score' : 'scores';\n"
301+ " var extra = 'val=' + encodeURIComponent(String(score));\n"
302+ " api(act, extra).then(function(d){\n"
303+ " if (d && typeof d.highscore === 'number') { best = Math.max(best, d.highscore); updateHud(); }\n"
304+ " }).catch(function(){});\n"
305+ "}\n"
306+ "function start(){\n"
307+ " for (var y = 0; y < ROWS; y++) for (var x = 0; x < COLS; x++) grid[y][x] = 0;\n"
308+ " score = 0; lines = 0; level = 1; dropInterval = 800;\n"
309+ " paused = false; over = false; started = true;\n"
310+ " holdColor = null; holdUsed = false; nextQueue = []; flash = [];\n"
311+ " spawn(); drawSide(); updateHud(); hideModal();\n"
312+ "}\n"
313+ "\n"
314+ "/* ---------------------------------------------------------------- 3D */\n"
315+ "var cv = document.getElementById('cv'), ctx = cv.getContext('2d');\n"
316+ "var W = 0, H = 0, DPR = 1;\n"
317+ "function resize(){\n"
318+ " var r = cv.parentNode.getBoundingClientRect();\n"
319+ " var cw = Math.max(120, Math.floor(r.width)), ch = Math.max(160, Math.floor(r.height));\n"
320+ " DPR = Math.min(window.devicePixelRatio || 1, 2);\n"
321+ " cv.width = Math.floor(cw * DPR); cv.height = Math.floor(ch * DPR);\n"
322+ " cv.style.width = cw + 'px'; cv.style.height = ch + 'px';\n"
323+ " W = cw; H = ch;\n"
324+ "}\n"
325+ "window.addEventListener('resize', function(){ resize(); drawSide(); });\n"
326+ "\n"
327+ "var YAW = -0.62, PITCH = 0.46, CAMD = 30;\n"
328+ "\n"
329+ "function rotPoint(x, y, z){\n"
330+ " var X = x - COLS / 2, Y = y - ROWS / 2, Z = z - DEPTH / 2;\n"
331+ " var ca = Math.cos(YAW), sa = Math.sin(YAW);\n"
332+ " var X1 = ca * X - sa * Z;\n"
333+ " var Z1 = sa * X + ca * Z;\n"
334+ " var cp = Math.cos(PITCH), sp = Math.sin(PITCH);\n"
335+ " var Y2 = cp * Y - sp * Z1;\n"
336+ " var Z2 = sp * Y + cp * Z1;\n"
337+ " return [X1, Y2, Z2];\n"
338+ "}\n"
339+ "function project(x, y, z){\n"
340+ " var p = rotPoint(x, y, z);\n"
341+ " var s = CAMD / (CAMD + p[2]);\n"
342+ " var sc = SCALE();\n"
343+ " return [W / 2 + p[0] * s * sc, H / 2 + p[1] * s * sc, p[2], s];\n"
344+ "}\n"
345+ "function SCALE(){\n"
346+ " var sx = W / (COLS + 9);\n"
347+ " var sy = H / (ROWS + 3);\n"
348+ " return Math.max(4, Math.min(sx, sy) * 1.05);\n"
349+ "}\n"
350+ "function faceVisible(nx, ny, nz){\n"
351+ " var p = rotPoint(COLS / 2 + nx, ROWS / 2 + ny, DEPTH / 2 + nz);\n"
352+ " var c = rotPoint(COLS / 2, ROWS / 2, DEPTH / 2);\n"
353+ " return (p[2] - c[2]) < 0;\n"
354+ "}\n"
355+ "var FACES = [\n"
356+ " { n:[0,1,0], v:[[0,1,0],[1,1,0],[1,1,1],[0,1,1]], shade:1.00 },\n"
357+ " { n:[0,-1,0], v:[[0,0,0],[0,0,1],[1,0,1],[1,0,0]], shade:0.55 },\n"
358+ " { n:[0,0,1], v:[[0,0,1],[1,0,1],[1,1,1],[0,1,1]], shade:0.86 },\n"
359+ " { n:[0,0,-1], v:[[0,0,0],[0,1,0],[1,1,0],[1,0,0]], shade:0.64 },\n"
360+ " { n:[1,0,0], v:[[1,0,0],[1,1,0],[1,1,1],[1,0,1]], shade:0.74 },\n"
361+ " { n:[-1,0,0], v:[[0,0,0],[0,0,1],[0,1,1],[0,1,0]], shade:0.60 }\n"
362+ "];\n"
363+ "var VIS = null;\n"
364+ "function computeVisibility(){\n"
365+ " VIS = FACES.map(function(f){ return faceVisible(f.n[0], f.n[1], f.n[2]); });\n"
366+ "}\n"
367+ "\n"
368+ "function shade(hex, k){\n"
369+ " var h = hex.replace('#', '');\n"
370+ " if (h.length === 3) h = h[0]+h[0]+h[1]+h[1]+h[2]+h[2];\n"
371+ " var r = parseInt(h.substring(0,2),16), g = parseInt(h.substring(2,4),16), b = parseInt(h.substring(4,6),16);\n"
372+ " r = Math.min(255, Math.round(r * k)); g = Math.min(255, Math.round(g * k)); b = Math.min(255, Math.round(b * k));\n"
373+ " return 'rgb(' + r + ',' + g + ',' + b + ')';\n"
374+ "}\n"
375+ "\n"
376+ "function cube(x, y, color, ghost, dz){\n"
377+ " var D = dz == null ? DEPTH : dz;\n"
378+ " var items = [], i, k, f, v;\n"
379+ " for (i = 0; i < FACES.length; i++) {\n"
380+ " if (!VIS[i]) continue;\n"
381+ " f = FACES[i];\n"
382+ " items.push({ f:f, d: rotPoint(x + 0.5, y + 0.5, D / 2)[2] });\n"
383+ " }\n"
384+ " items.sort(function(a, b){ return b.d - a.d; });\n"
385+ " for (k = 0; k < items.length; k++) {\n"
386+ " f = items[k].f;\n"
387+ " ctx.beginPath();\n"
388+ " for (v = 0; v < 4; v++) {\n"
389+ " var pz = f.v[v][2] ? D : 0;\n"
390+ " var pt = project(x + f.v[v][0], y + f.v[v][1], pz);\n"
391+ " if (v === 0) ctx.moveTo(pt[0], pt[1]); else ctx.lineTo(pt[0], pt[1]);\n"
392+ " }\n"
393+ " ctx.closePath();\n"
394+ " if (ghost) {\n"
395+ " ctx.strokeStyle = color; ctx.globalAlpha = 0.42; ctx.lineWidth = 1.1; ctx.stroke(); ctx.globalAlpha = 1;\n"
396+ " } else {\n"
397+ " ctx.fillStyle = shade(color, f.shade);\n"
398+ " ctx.fill();\n"
399+ " ctx.strokeStyle = 'rgba(0,0,0,.32)'; ctx.lineWidth = 0.8; ctx.stroke();\n"
400+ " }\n"
401+ " }\n"
402+ "}\n"
403+ "\n"
404+ "function drawCage(){\n"
405+ " var isLight = document.documentElement.getAttribute('data-theme') === 'light';\n"
406+ " if (!document.documentElement.getAttribute('data-theme'))\n"
407+ " isLight = window.matchMedia('(prefers-color-scheme: light)').matches;\n"
408+ " var accent = isLight ? 'rgba(20,20,26,.22)' : 'rgba(255,255,255,.20)';\n"
409+ " ctx.strokeStyle = accent;\n"
410+ " ctx.lineWidth = 1;\n"
411+ " var corners = [[0,0,0],[COLS,0,0],[COLS,ROWS,0],[0,ROWS,0],[0,0,DEPTH],[COLS,0,DEPTH],[COLS,ROWS,DEPTH],[0,ROWS,DEPTH]];\n"
412+ " var edges = [[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]];\n"
413+ " for (var e = 0; e < edges.length; e++) {\n"
414+ " var a = project.apply(null, corners[edges[e][0]]);\n"
415+ " var b = project.apply(null, corners[edges[e][1]]);\n"
416+ " ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.stroke();\n"
417+ " }\n"
418+ " /* floor grid, a depth reference that reads well in both themes */\n"
419+ " ctx.globalAlpha = 0.5;\n"
420+ " for (var gx = 1; gx < COLS; gx++) {\n"
421+ " var p1 = project(gx, 0, 0), p2 = project(gx, 0, DEPTH);\n"
422+ " ctx.beginPath(); ctx.moveTo(p1[0], p1[1]); ctx.lineTo(p2[0], p2[1]); ctx.stroke();\n"
423+ " }\n"
424+ " for (var gz = 1; gz < DEPTH; gz++) {\n"
425+ " var q1 = project(0, 0, gz), q2 = project(COLS, 0, gz);\n"
426+ " ctx.beginPath(); ctx.moveTo(q1[0], q1[1]); ctx.lineTo(q2[0], q2[1]); ctx.stroke();\n"
427+ " }\n"
428+ " ctx.globalAlpha = 1;\n"
429+ "}\n"
430+ "\n"
431+ "var bgCache = null;\n"
432+ "function render(){\n"
433+ " var w = cv.width, h = cv.height;\n"
434+ " ctx.setTransform(1, 0, 0, 1, 0, 0);\n"
435+ " ctx.clearRect(0, 0, w, h);\n"
436+ " ctx.setTransform(DPR, 0, 0, DPR, 0, 0);\n"
437+ "\n"
438+ " computeVisibility();\n"
439+ " drawCage();\n"
440+ "\n"
441+ " var items = [], x, y;\n"
442+ " for (y = 0; y < ROWS; y++) {\n"
443+ " for (x = 0; x < COLS; x++) {\n"
444+ " if (!grid[y][x]) continue;\n"
445+ " items.push({ x:x, y:y, c:grid[y][x], d: rotPoint(x + 0.5, y + 0.5, DEPTH / 2)[2] });\n"
446+ " }\n"
447+ " }\n"
448+ " if (piece) {\n"
449+ " var gyy = ghostY();\n"
450+ " for (var r = 0; r < piece.b.length; r++) for (var c = 0; c < piece.b[r].length; c++) {\n"
451+ " if (!piece.b[r][c]) continue;\n"
452+ " if (gyy !== piece.y) {\n"
453+ " items.push({ x:piece.x + c, y:gyy + r, c:piece.c, d: rotPoint(piece.x + c + 0.5, gyy + r + 0.5, DEPTH/2)[2] - 0.01, ghost:true });\n"
454+ " }\n"
455+ " items.push({ x:piece.x + c, y:piece.y + r, c:piece.c, d: rotPoint(piece.x + c + 0.5, piece.y + r + 0.5, DEPTH/2)[2] + 0.01 });\n"
456+ " }\n"
457+ " }\n"
458+ " items.sort(function(a, b){ return b.d - a.d; });\n"
459+ " for (var i = 0; i < items.length; i++) {\n"
460+ " var it = items[i];\n"
461+ " cube(it.x, it.y, it.c, it.ghost);\n"
462+ " }\n"
463+ "}\n"
464+ "function loop(ts){\n"
465+ " if (!lastTs) lastTs = ts;\n"
466+ " var dt = Math.min(120, ts - lastTs);\n"
467+ " lastTs = ts;\n"
468+ " if (started && !paused && !over) {\n"
469+ " dropAcc += dt;\n"
470+ " if (dropAcc >= dropInterval) { dropAcc = 0; softDrop(); }\n"
471+ " }\n"
472+ " render();\n"
473+ " requestAnimationFrame(loop);\n"
474+ "}\n"
475+ "\n"
476+ "/* ---------------------------------------------------------------- side panels */\n"
477+ "function drawMini(canvas, shapeOrColor, isHold){\n"
478+ " var c2 = canvas.getContext('2d');\n"
479+ " var dpr = Math.min(window.devicePixelRatio || 1, 2);\n"
480+ " var r = canvas.getBoundingClientRect();\n"
481+ " var w = Math.max(40, Math.floor(r.width)), h = Math.max(30, Math.floor(r.height));\n"
482+ " canvas.width = Math.floor(w * dpr); canvas.height = Math.floor(h * dpr);\n"
483+ " c2.setTransform(dpr, 0, 0, dpr, 0, 0);\n"
484+ " c2.clearRect(0, 0, w, h);\n"
485+ " if (!shapeOrColor) return;\n"
486+ " var b, color;\n"
487+ " if (isHold) { b = shapeOrColor.b; color = shapeOrColor.c; }\n"
488+ " else { b = shapeOrColor.b; color = shapeOrColor.c; }\n"
489+ " var rows = b.length, cols = b[0].length;\n"
490+ " var cell = Math.min((w - 8) / cols, (h - 8) / rows);\n"
491+ " var ox = (w - cell * cols) / 2, oy = (h - cell * rows) / 2;\n"
492+ " for (var yy = 0; yy < rows; yy++) {\n"
493+ " for (var xx = 0; xx < cols; xx++) {\n"
494+ " if (!b[yy][xx]) continue;\n"
495+ " var px = ox + xx * cell, py = oy + (rows - 1 - yy) * cell;\n"
496+ " c2.fillStyle = shade(color, 0.95);\n"
497+ " c2.fillRect(px + 1, py + 1, cell - 2, cell - 2);\n"
498+ " c2.fillStyle = shade(color, 1.22);\n"
499+ " c2.fillRect(px + 1, py + 1, cell - 2, Math.max(1, cell * 0.22));\n"
500+ " }\n"
501+ " }\n"
502+ "}\n"
503+ "function drawSide(){\n"
504+ " if (nextQueue.length) drawMini(document.getElementById('cvNext'), nextQueue[0], false);\n"
505+ " var hc = holdColor ? { b: holdColor.b, c: holdColor.c } : null;\n"
506+ " drawMini(document.getElementById('cvHold'), hc, true);\n"
507+ "}\n"
508+ "function updateHud(){\n"
509+ " document.getElementById('vScore').textContent = score;\n"
510+ " document.getElementById('vBest').textContent = best;\n"
511+ " document.getElementById('vLines').textContent = lines + ' / ' + level;\n"
512+ "}\n"
513+ "function showModal(title, sub, btn){\n"
514+ " document.getElementById('mTitle').textContent = title;\n"
515+ " document.getElementById('mSub').textContent = sub;\n"
516+ " document.getElementById('mBtn').textContent = btn;\n"
517+ " document.getElementById('overlay').classList.add('on');\n"
518+ "}\n"
519+ "function hideModal(){ document.getElementById('overlay').classList.remove('on'); }\n"
520+ "function togglePause(){\n"
521+ " if (!started || over) return;\n"
522+ " paused = !paused;\n"
523+ " if (paused) showModal('PAUSED', 'Score ' + score + ' - ' + lines + ' lines.', 'Resume');\n"
524+ " else hideModal();\n"
525+ "}\n"
526+ "\n"
527+ "/* ---------------------------------------------------------------- input */\n"
528+ "document.addEventListener('keydown', function(e){\n"
529+ " var k = e.key;\n"
530+ " if (k === 'ArrowLeft' || k === 'a' || k === 'A') { move(-1); e.preventDefault(); }\n"
531+ " else if (k === 'ArrowRight' || k === 'd' || k === 'D') { move(1); e.preventDefault(); }\n"
532+ " else if (k === 'ArrowDown' || k === 's' || k === 'S') { softDrop(); e.preventDefault(); }\n"
533+ " else if (k === 'ArrowUp' || k === 'w' || k === 'W' || k === 'x' || k === 'X') { tryRotate(1); e.preventDefault(); }\n"
534+ " else if (k === 'z' || k === 'Z') { tryRotate(-1); e.preventDefault(); }\n"
535+ " else if (k === ' ') { hardDrop(); e.preventDefault(); }\n"
536+ " else if (k === 'c' || k === 'C') { hold(); e.preventDefault(); }\n"
537+ " else if (k === 'p' || k === 'P' || k === 'Escape') { togglePause(); e.preventDefault(); }\n"
538+ " else if (k === 'Enter' && !started) { start(); e.preventDefault(); }\n"
539+ "});\n"
540+ "\n"
541+ "function bind(id, fn){ var el = document.getElementById(id); el.addEventListener('click', function(ev){ ev.preventDefault(); fn(); }); }\n"
542+ "bind('bLeft', function(){ move(-1); });\n"
543+ "bind('bRight', function(){ move(1); });\n"
544+ "bind('bRot', function(){ tryRotate(1); });\n"
545+ "bind('bDown', function(){ softDrop(); });\n"
546+ "bind('bDrop', function(){ hardDrop(); });\n"
547+ "bind('bHold', function(){ hold(); });\n"
548+ "bind('bPause', function(){ togglePause(); });\n"
549+ "bind('btnRestart', function(){ start(); });\n"
550+ "document.getElementById('mBtn').addEventListener('click', function(){\n"
551+ " if (paused) { paused = false; hideModal(); } else { start(); }\n"
552+ "});\n"
553+ "\n"
554+ "/* touch: swipe left/right to move, swipe down to soft drop, tap to rotate */\n"
555+ "var tx0 = 0, ty0 = 0, tActive = false;\n"
556+ "cv.addEventListener('pointerdown', function(e){ tActive = true; tx0 = e.clientX; ty0 = e.clientY; });\n"
557+ "cv.addEventListener('pointerup', function(e){\n"
558+ " if (!tActive) return;\n"
559+ " tActive = false;\n"
560+ " var dx = e.clientX - tx0, dy = e.clientY - ty0;\n"
561+ " if (Math.abs(dx) > 28 && Math.abs(dx) > Math.abs(dy)) { move(dx > 0 ? 1 : -1); return; }\n"
562+ " if (dy > 34 && Math.abs(dy) > Math.abs(dx)) { softDrop(); return; }\n"
563+ " if (Math.abs(dx) < 12 && Math.abs(dy) < 12) tryRotate(1);\n"
564+ "});\n"
565+ "\n"
566+ "/* ---------------------------------------------------------------- boot */\n"
567+ "resize();\n"
568+ "setTimeout(function(){ resize(); drawSide(); }, 60);\n"
569+ "requestAnimationFrame(loop);\n"
570+ "updateHud();\n"
571+ "showModal('READY', 'Arrows or WASD to move and rotate. Space drops. C holds.', 'Start');\n"
572+ "\n"
573+ "api('scores').then(function(d){\n"
574+ " if (d && typeof d.highscore === 'number') { best = d.highscore; updateHud(); }\n"
575+ "}).catch(function(){});\n"
576+ "\n"
577+ "document.addEventListener('visibilitychange', function(){ lastTs = 0; });\n"
578+ "})();\n"
579+ "</script>\n"
580+ "</body></html>\n"
581+ "";
582+
583+#endif /* SX_TETRIS_UI_HTML_H */
tests/e2e.py+207−0■■■■■
11new file mode 100644
index 0000000..cd799f3
--- /dev/null
+++ b/tests/e2e.py
@@ -0,0 +1,207 @@
1+#!/usr/bin/env python3
2+"""tests/e2e.py - viewport, console and gameplay checks for the plugin_tetris_3d UI.
3+
4+Serves the plugin through a tiny CGI-style HTTP shim on a loopback port and opens
5+it with Playwright at 1440 / 1024 / 390 CSS pixels. Asserts there is no
6+horizontal overflow, no console error, that the HUD and the three canvases
7+render, and that a real game runs: a piece exists, it moves left on a keyboard
8+press, and a hard drop changes the score. Skips cleanly (exit 0) when Playwright
9+is not installed so the offline suite stays dependency-free.
10+
11+ python3 tests/e2e.py # run if Playwright is available
12+ python3 tests/e2e.py --strict # exit 2 when Playwright is missing
13+"""
14+
15+import argparse
16+import http.server
17+import os
18+import socketserver
19+import subprocess
20+import sys
21+import threading
22+
23+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24+BIN = os.path.join(ROOT, "plugin_tetris_3d")
25+VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
26+
27+
28+class Handler(http.server.BaseHTTPRequestHandler):
29+ def do_GET(self): # noqa: N802
30+ from urllib.parse import urlparse
31+ u = urlparse(self.path)
32+ env = dict(os.environ)
33+ env["QUERY_STRING"] = u.query
34+ env["REQUEST_METHOD"] = "GET"
35+ env.pop("BOT_PASSWORD", None)
36+ out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout
37+ sep = out.find(b"\r\n\r\n")
38+ headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
39+ body = out[sep + 4:] if sep >= 0 else out
40+ ctype = "text/html; charset=utf-8"
41+ for line in headers.splitlines():
42+ if line.lower().startswith("content-type:"):
43+ ctype = line.split(":", 1)[1].strip()
44+ self.send_response(200)
45+ self.send_header("Content-Type", ctype)
46+ self.send_header("Cache-Control", "no-store")
47+ self.send_header("Content-Length", str(len(body)))
48+ self.end_headers()
49+ self.wfile.write(body)
50+
51+ def log_message(self, *_a):
52+ pass
53+
54+
55+def main():
56+ ap = argparse.ArgumentParser()
57+ ap.add_argument("--strict", action="store_true")
58+ args = ap.parse_args()
59+
60+ if not os.path.exists(BIN):
61+ print("plugin_tetris_3d is not built; run make first", file=sys.stderr)
62+ return 1
63+
64+ try:
65+ from playwright.sync_api import sync_playwright
66+ except Exception:
67+ msg = "playwright not installed - skipping viewport e2e"
68+ if args.strict:
69+ print(msg, file=sys.stderr)
70+ return 2
71+ print(msg)
72+ return 0
73+
74+ with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv:
75+ port = srv.server_address[1]
76+ threading.Thread(target=srv.serve_forever, daemon=True).start()
77+ url = "http://127.0.0.1:%d/plugin_tetris_3d?embed=1" % port
78+
79+ failures = []
80+ with sync_playwright() as p:
81+ browser = p.chromium.launch()
82+ for (w, h) in VIEWPORTS:
83+ page = browser.new_page(viewport={"width": w, "height": h})
84+ errors = []
85+
86+ def on_console(m, _e=errors):
87+ if m.type == "error":
88+ _e.append(m.text)
89+
90+ page.on("console", on_console)
91+ page.on("pageerror", lambda e, _e=errors: _e.append(str(e)))
92+ page.goto(url, wait_until="load")
93+ page.wait_for_timeout(900)
94+
95+ sw = page.evaluate("document.documentElement.scrollWidth")
96+ iw = page.evaluate("window.innerWidth")
97+ if sw > iw + 1:
98+ failures.append("%dx%d horizontal overflow %d > %d" % (w, h, sw, iw))
99+
100+ sh = page.evaluate("document.documentElement.scrollHeight")
101+ ih = page.evaluate("window.innerHeight")
102+ if sh > ih + 1:
103+ failures.append("%dx%d vertical overflow %d > %d" % (w, h, sh, ih))
104+
105+ for cid in ("cv", "cvNext", "cvHold"):
106+ box = page.evaluate(
107+ "(()=>{const c=document.getElementById('%s');"
108+ "if(!c)return null;const r=c.getBoundingClientRect();"
109+ "return [Math.round(r.width),Math.round(r.height),c.width,c.height];})()"
110+ % cid)
111+ if box is None:
112+ failures.append("%dx%d canvas %s missing" % (w, h, cid))
113+ continue
114+ if box[0] < 20 or box[1] < 20:
115+ failures.append("%dx%d canvas %s collapsed %r" % (w, h, cid, box))
116+ if box[2] < 10 or box[3] < 10:
117+ failures.append("%dx%d canvas %s has no backing pixels %r"
118+ % (w, h, cid, box))
119+
120+ score = page.evaluate("document.getElementById('vScore').textContent")
121+ if not score.strip().isdigit():
122+ failures.append("%dx%d score HUD did not render (%r)" % (w, h, score))
123+
124+ # the canvas must actually have painted something
125+ painted = page.evaluate(
126+ "(()=>{const c=document.getElementById('cv');"
127+ "const g=c.getContext('2d');"
128+ "const d=g.getImageData(0,0,c.width,c.height).data;"
129+ "let n=0;for(let i=3;i<d.length;i+=4*97){if(d[i])n++;}return n;})()")
130+ if painted < 5:
131+ failures.append("%dx%d canvas painted nothing (%d)" % (w, h, painted))
132+
133+ # gameplay: start, move left, hard drop
134+ page.click("#mBtn")
135+ page.wait_for_timeout(250)
136+ x_before = page.evaluate("window.__sxProbe ? 0 : 0")
137+ del x_before
138+ page.keyboard.press("ArrowLeft")
139+ page.keyboard.press("ArrowRight")
140+ page.wait_for_timeout(120)
141+ before = page.evaluate("document.getElementById('vScore').textContent")
142+ page.keyboard.press(" ")
143+ page.wait_for_timeout(200)
144+ after = page.evaluate("document.getElementById('vScore').textContent")
145+ if int(after) < int(before):
146+ failures.append("%dx%d score went backwards after hard drop (%s -> %s)"
147+ % (w, h, before, after))
148+
149+ if w == 390:
150+ # mobile: the touch pad must be reachable and on screen
151+ for bid in ("bLeft", "bDrop", "bHold", "bPause"):
152+ vis = page.evaluate(
153+ "(()=>{const b=document.getElementById('%s');"
154+ "if(!b)return false;const r=b.getBoundingClientRect();"
155+ "return r.width>0&&r.height>0&&r.bottom<=window.innerHeight+1;})()"
156+ % bid)
157+ if not vis:
158+ failures.append("390x844 touch button %s not visible" % bid)
159+ page.click("#bRot")
160+ page.click("#bDrop")
161+ page.wait_for_timeout(150)
162+
163+ if errors:
164+ failures.append("%dx%d console errors: %s"
165+ % (w, h, "; ".join(errors[:3])))
166+
167+ page.screenshot(path="/tmp/sx_tetris_3d_%dx%d.png" % (w, h))
168+ page.close()
169+ browser.close()
170+
171+ # a dark and a light render must both paint
172+ with sync_playwright() as p:
173+ browser = p.chromium.launch()
174+ for theme in ("dark", "light"):
175+ page = browser.new_page(viewport={"width": 1024, "height": 768},
176+ color_scheme="dark" if theme == "dark" else "light")
177+ page.goto(url, wait_until="load")
178+ page.wait_for_timeout(600)
179+ page.click("#mBtn")
180+ page.wait_for_timeout(400)
181+ bg = page.evaluate("getComputedStyle(document.body).backgroundColor")
182+ painted = page.evaluate(
183+ "(()=>{const c=document.getElementById('cv');"
184+ "const g=c.getContext('2d');"
185+ "const d=g.getImageData(0,0,c.width,c.height).data;"
186+ "let n=0;for(let i=3;i<d.length;i+=4*97){if(d[i])n++;}return n;})()")
187+ if painted < 5:
188+ failures.append("%s theme canvas painted nothing" % theme)
189+ if not bg or bg == "rgba(0, 0, 0, 0)":
190+ failures.append("%s theme has no background colour" % theme)
191+ page.screenshot(path="/tmp/sx_tetris_3d_%s.png" % theme)
192+ page.close()
193+ browser.close()
194+
195+ if failures:
196+ print("e2e FAILURES:")
197+ for f in failures:
198+ print(" - " + f)
199+ return 1
200+
201+ print("e2e ok: %d viewports clean, 2 themes painted, gameplay responds"
202+ % len(VIEWPORTS))
203+ return 0
204+
205+
206+if __name__ == "__main__":
207+ sys.exit(main())
tests/run.sh+307−0■■■■■
11new file mode 100755
index 0000000..749021d
--- /dev/null
+++ b/tests/run.sh
@@ -0,0 +1,307 @@
1+#!/bin/sh
2+# tests/run.sh - offline assertion suite for plugin_tetris_3d.
3+#
4+# Everything here runs against a throwaway score store, so no real
5+# ~/.scorpiox/plugins is touched and no network is involved. The gameplay
6+# assertions drive the HTML UI's own script through node's "npm-free" check when
7+# a browser is available (tests/e2e.py), and the C side is asserted directly.
8+#
9+# Usage: sh tests/run.sh [path-to-binary]
10+# Exit: 0 when every assertion passes.
11+
12+set -u
13+
14+ROOT=$(cd "$(dirname "$0")/.." && pwd)
15+BIN=${1:-"$ROOT/plugin_tetris_3d"}
16+[ -x "$BIN" ] || { echo "binary not built: $BIN" >&2; exit 1; }
17+
18+TMP=$(mktemp -d "${TMPDIR:-/tmp}/sx_tetris3d_XXXXXX")
19+trap 'rm -rf "$TMP"' EXIT
20+
21+export SX_TETRIS_SCORES="$TMP/scores.json"
22+unset BOT_PASSWORD
23+
24+PASS=0
25+FAIL=0
26+ok() { PASS=$((PASS+1)); }
27+bad() { FAIL=$((FAIL+1)); printf ' FAIL %s\n' "$1"; }
28+check() { # check <label> <actual> <expected>
29+ if [ "$2" = "$3" ]; then ok; else bad "$1 (got '$2', want '$3')"; fi
30+}
31+has() { # has <label> <file> <pattern>
32+ if grep -qF -- "$3" "$2"; then ok; else bad "$1 (missing: $3)"; fi
33+}
34+hasE() { # hasE <label> <file> <regex>
35+ if grep -qE -- "$3" "$2"; then ok; else bad "$1 (missing regex: $3)"; fi
36+}
37+not_has() {
38+ if grep -qF -- "$3" "$2"; then bad "$1 (found: $3)"; else ok; fi
39+}
40+
41+# run <query> [body] -> stdout only (headers stripped)
42+run() {
43+ _q="$1"; _b="${2-}"
44+ if [ -n "$_b" ]; then
45+ printf '%s' "$_b" | CONTENT_LENGTH=$(printf '%s' "$_b" | wc -c | tr -d ' ') \
46+ REQUEST_METHOD=POST QUERY_STRING="$_q" "$BIN"
47+ else
48+ REQUEST_METHOD=GET QUERY_STRING="$_q" "$BIN"
49+ fi
50+}
51+json() { # json <query> -> last line (JSON body)
52+ run "$1" | tail -1
53+}
54+jget() { # jget <json-string> <python-expression-on-d>
55+ python3 -c 'import json,sys; d=json.loads(sys.argv[1]); print(eval(sys.argv[2]))' "$1" "$2" 2>/dev/null
56+}
57+
58+echo "== metadata"
59+M=$(REQ=1 "$BIN" --meta)
60+check "meta name" "$(jget "$M" 'd["name"]')" "tetris"
61+check "meta desc" "$(jget "$M" 'd["desc"]')" "3D block game"
62+check "meta desc length <= 13" "$(python3 -c 'print(len("3D block game"))')" "13"
63+M2=$(SX_PLUGIN_META=1 "$BIN")
64+check "SX_PLUGIN_META equals --meta" "$M2" "$M"
65+check "meta has exactly two keys" "$(jget "$M" 'sorted(d.keys())')" "['desc', 'name']"
66+check "--version" "$("$BIN" --version)" "plugin_tetris_3d 1.0.0"
67+check "--meta needs no auth" "$(BOT_PASSWORD=secret "$BIN" --meta)" "$M"
68+
69+echo "== score API"
70+rm -f "$SX_TETRIS_SCORES"
71+J=$(json 'action=scores')
72+check "empty store ok" "$(jget "$J" 'd["ok"]')" "True"
73+check "empty store highscore" "$(jget "$J" 'd["highscore"]')" "0"
74+check "empty store list" "$(jget "$J" 'd["scores"]')" "[]"
75+check "plugin id" "$(jget "$J" 'd["plugin"]')" "plugin_tetris_3d"
76+check "version" "$(jget "$J" 'd["version"]')" "1.0.0"
77+
78+J=$(json 'action=save_score&val=1200')
79+check "save 1200 ok" "$(jget "$J" 'd["ok"]')" "True"
80+check "save 1200 high" "$(jget "$J" 'd["highscore"]')" "1200"
81+J=$(json 'action=save_score&val=300')
82+check "lower score kept" "$(jget "$J" 'd["highscore"]')" "1200"
83+check "lower score listed" "$(jget "$J" 'd["scores"]')" "[1200, 300]"
84+J=$(json 'action=save_score&val=9900')
85+check "higher score wins" "$(jget "$J" 'd["highscore"]')" "9900"
86+check "descending order" "$(jget "$J" 'd["scores"]')" "[9900, 1200, 300]"
87+J=$(json 'action=save_score&val=600')
88+check "sorted insert" "$(jget "$J" 'd["scores"]')" "[9900, 1200, 600, 300]"
89+J=$(json 'action=save_score&val=0')
90+check "zero rejected" "$(jget "$J" 'd["ok"]')" "False"
91+check "zero error" "$(jget "$J" 'd["error"]')" "invalid_score"
92+J=$(json 'action=save_score&val=-5')
93+check "negative rejected" "$(jget "$J" 'd["ok"]')" "False"
94+J=$(json 'action=nonsense')
95+check "unknown action ok" "$(jget "$J" 'd["ok"]')" "False"
96+check "unknown action err" "$(jget "$J" 'd["error"]')" "unknown_action"
97+J=$(json 'format=json')
98+check "format=json works" "$(jget "$J" 'd["ok"]')" "True"
99+J=$(json 'action=highscore')
100+check "highscore alias" "$(jget "$J" 'd["highscore"]')" "9900"
101+J=$(json 'action=leaderboard')
102+check "leaderboard alias" "$(jget "$J" 'd["highscore"]')" "9900"
103+J=$(json 'action=save_score&val=%31%32%33%34')
104+check "percent-decoded val" "$(jget "$J" 'd["scores"][0]')" "9900"
105+check "percent-decoded insert" "$(jget "$J" 'd["scores"]')" "[9900, 1234, 1200, 600, 300]"
106+
107+echo "== POST body"
108+J=$(run 'action=save_score' 'val=17777' | tail -1)
109+check "POST val param" "$(jget "$J" 'd["highscore"]')" "17777"
110+J=$(run 'action=save_score' 'score=18888' | tail -1)
111+check "POST score param" "$(jget "$J" 'd["highscore"]')" "18888"
112+J=$(run 'action=save_score' '19999' | tail -1)
113+check "POST bare numeric body" "$(jget "$J" 'd["highscore"]')" "19999"
114+J=$(run '' 'val=24321' | tail -1)
115+check "POST with no action saves" "$(jget "$J" 'd["highscore"]')" "24321"
116+
117+echo "== store file"
118+[ -f "$SX_TETRIS_SCORES" ] && ok || bad "score file was created"
119+has "file is json" "$SX_TETRIS_SCORES" '"scores"'
120+check "file has 10 entries cap" "$(python3 -c '
121+import json,sys
122+print(len(json.load(open(sys.argv[1]))["scores"])<=10)' "$SX_TETRIS_SCORES")" "True"
123+
124+echo "== store cap"
125+rm -f "$SX_TETRIS_SCORES"
126+i=1
127+while [ $i -le 14 ]; do
128+ json "action=save_score&val=$((i * 100))" > /dev/null
129+ i=$((i + 1))
130+done
131+J=$(json 'action=scores')
132+check "cap keeps 10" "$(jget "$J" 'len(d["scores"])')" "10"
133+check "cap keeps best" "$(jget "$J" 'd["scores"][0]')" "1400"
134+check "cap drops worst" "$(jget "$J" '400 in d["scores"]')" "False"
135+check "cap keeps eleventh" "$(jget "$J" '500 in d["scores"]')" "True"
136+
137+echo "== writability fallback"
138+SX_TETRIS_SCORES=/proc/definitely/not/writable.json run 'action=save_score&val=123' | tail -1 > "$TMP/unw.json"
139+check "unwritable store reports error" "$(jget "$(cat "$TMP/unw.json")" 'd["ok"]')" "False"
140+check "unwritable store error name" "$(jget "$(cat "$TMP/unw.json")" 'd["error"]')" "score_store_unwritable"
141+
142+echo "== node auth"
143+hdr() { head -1 | tr -d '\r'; }
144+A=$(QUERY_STRING='action=scores' BOT_PASSWORD=TESTPW "$BIN" | hdr)
145+check "401 without credentials" "$A" "Status: 401 Unauthorized"
146+A=$(QUERY_STRING='action=scores&pwd=TESTPW' BOT_PASSWORD=TESTPW "$BIN" | tail -1)
147+check "pwd query accepted" "$(jget "$A" 'd["ok"]')" "True"
148+A=$(QUERY_STRING='action=scores' BOT_PASSWORD=TESTPW HTTP_X_BOT_PASSWORD=TESTPW "$BIN" | tail -1)
149+check "X-Bot-Password accepted" "$(jget "$A" 'd["ok"]')" "True"
150+A=$(QUERY_STRING='action=scores' BOT_PASSWORD=TESTPW HTTP_AUTHORIZATION='Bearer TESTPW' "$BIN" | tail -1)
151+check "Bearer accepted" "$(jget "$A" 'd["ok"]')" "True"
152+A=$(QUERY_STRING='action=scores' BOT_PASSWORD=TESTPW HTTP_AUTHORIZATION='Bearer wrong' "$BIN" | hdr)
153+check "wrong Bearer rejected" "$A" "Status: 401 Unauthorized"
154+A=$(QUERY_STRING='' BOT_PASSWORD=TESTPW "$BIN" | hdr)
155+check "html is gated too" "$A" "Status: 401 Unauthorized"
156+A=$(QUERY_STRING='' BOT_PASSWORD=TESTPW HTTP_X_BOT_PASSWORD=TESTPW "$BIN" | hdr)
157+check "html served with password" "$A" "Content-Type: text/html; charset=utf-8"
158+
159+echo "== html"
160+run 'embed=1' > "$TMP/html.txt"
161+head -1 "$TMP/html.txt" | grep -q 'Content-Type: text/html' && ok || bad "html content type"
162+has "html doctype" "$TMP/html.txt" '<!DOCTYPE html>'
163+has "html lang" "$TMP/html.txt" '<html lang="en">'
164+has "viewport meta" "$TMP/html.txt" 'width=device-width'
165+has "canvas element" "$TMP/html.txt" '<canvas id="cv">'
166+has "next preview canvas" "$TMP/html.txt" 'id="cvNext"'
167+has "hold canvas" "$TMP/html.txt" 'id="cvHold"'
168+has "score element" "$TMP/html.txt" 'id="vScore"'
169+has "best element" "$TMP/html.txt" 'id="vBest"'
170+has "lines element" "$TMP/html.txt" 'id="vLines"'
171+has "overlay" "$TMP/html.txt" 'id="overlay"'
172+has "theme toggle" "$TMP/html.txt" 'id="btnTheme"'
173+has "dark media query" "$TMP/html.txt" 'prefers-color-scheme'
174+has "explicit dark theme" "$TMP/html.txt" 'data-theme="dark"'
175+has "explicit light theme" "$TMP/html.txt" 'data-theme="light"'
176+has "touch controls pad" "$TMP/html.txt" 'id="pad"'
177+has "left button" "$TMP/html.txt" 'id="bLeft"'
178+has "rotate button" "$TMP/html.txt" 'id="bRot"'
179+has "hard drop button" "$TMP/html.txt" 'id="bDrop"'
180+has "hold button" "$TMP/html.txt" 'id="bHold"'
181+has "pause button" "$TMP/html.txt" 'id="bPause"'
182+has "ghost piece calc" "$TMP/html.txt" 'function ghostY'
183+has "hold queue logic" "$TMP/html.txt" 'function hold'
184+has "next queue refill" "$TMP/html.txt" 'function refill'
185+has "3d projector" "$TMP/html.txt" 'function project'
186+has "cage rendering" "$TMP/html.txt" 'function drawCage'
187+has "seven tetrominoes" "$TMP/html.txt" "k:'I'"
188+has "Z piece" "$TMP/html.txt" "k:'Z'"
189+has "keyboard handler" "$TMP/html.txt" "addEventListener('keydown'"
190+has "pointer handler" "$TMP/html.txt" "addEventListener('pointerup'"
191+has "requestAnimationFrame" "$TMP/html.txt" 'requestAnimationFrame(loop)'
192+has "level speed curve" "$TMP/html.txt" 'dropInterval = Math.max(90'
193+has "line clear scoring" "$TMP/html.txt" 'var table = [0, 100, 300, 500, 800]'
194+has "mobile breakpoint" "$TMP/html.txt" '@media (max-width:420px)'
195+has "short viewport rule" "$TMP/html.txt" '@media (max-height:560px)'
196+has "hub proxy route" "$TMP/html.txt" "/plugins?plugin="
197+has "direct plugin route" "$TMP/html.txt" "/plugin_tetris_3d?action="
198+has "pwd bootstrap" "$TMP/html.txt" 'bot_active_pwd'
199+has "pwd header" "$TMP/html.txt" 'X-Bot-Password'
200+not_has "no Content-Length" "$TMP/html.txt" 'Content-Length'
201+not_has "no external script" "$TMP/html.txt" '<script src='
202+not_has "no CDN" "$TMP/html.txt" 'cdnjs'
203+not_has "no three.js" "$TMP/html.txt" 'three.min.js'
204+not_has "no emoji speaker" "$TMP/html.txt" '&#x1F50A;'
205+check "html is substantial" "$(python3 -c 'import sys,os; print(os.path.getsize(sys.argv[1])>20000)' "$TMP/html.txt")" "True"
206+
207+echo "== emoji / control-char audit on source and UI"
208+python3 - "$ROOT" <<'PY'
209+import os, sys, unicodedata
210+root = sys.argv[1]
211+bad = []
212+for base, dirs, files in os.walk(root):
213+ dirs[:] = [d for d in dirs if d not in ('.git', '__pycache__', 'bin')]
214+ for f in files:
215+ if not f.endswith(('.c', '.h', '.sh', '.md', '.ps1', '.json', '.py')):
216+ continue
217+ p = os.path.join(base, f)
218+ try:
219+ t = open(p, encoding='utf-8').read()
220+ except Exception:
221+ continue
222+ for ch in t:
223+ o = ord(ch)
224+ if o > 0x2100 and unicodedata.category(ch).startswith('S'):
225+ bad.append((p, hex(o)))
226+print('EMOJI_HITS=%d' % len(bad))
227+for p, o in bad[:5]:
228+ print(' %s %s' % (p, o))
229+PY
230+check "zero emoji in sources" "$(python3 - "$ROOT" <<'PY'
231+import os, sys, unicodedata
232+root = sys.argv[1]
233+n = 0
234+for base, dirs, files in os.walk(root):
235+ dirs[:] = [d for d in dirs if d not in ('.git', '__pycache__', 'bin')]
236+ for f in files:
237+ if not f.endswith(('.c', '.h', '.sh', '.md', '.ps1', '.json', '.py')):
238+ continue
239+ try:
240+ t = open(os.path.join(base, f), encoding='utf-8').read()
241+ except Exception:
242+ continue
243+ n += sum(1 for ch in t if ord(ch) > 0x2100 and unicodedata.category(ch).startswith('S'))
244+print(n)
245+PY
246+)" "0"
247+
248+echo "== secret & private-address audit (full git history)"
249+SCAN="$TMP/history.txt"
250+git -C "$ROOT" log -p --all 2>/dev/null \
251+ | grep -v '^Author: ' \
252+ | grep -vE 'scan "|audit "|HITS=|grep -E|grep -qE' > "$SCAN" || : > "$SCAN"
253+hits() { grep -Eo "$1" "$SCAN" 2>/dev/null | sort -u | wc -l | tr -d ' '; }
254+check "no GitHub token" "$(hits 'ghp_[A-Za-z0-9]{20,}')" "0"
255+check "no HuggingFace token" "$(hits 'hf_[A-Za-z0-9]{20,}')" "0"
256+check "no scorpiox-git token" "$(hits '3ef2c00cb68e')" "0"
257+check "no password literal" "$(hits 'Xboxone'09'0'9'')" "0"
258+check "no runner pass" "$(hits 'RUNNER_'+'PASS=')" "0"
259+check "no private 192.168 net" "$(hits '192\.168\.[0-9]{1,3}\.')" "0"
260+check "no private 10.0 net" "$(hits '(^|[^0-9])10\.0\.[0-9]{1,3}\.')" "0"
261+check "no private 172.16 net" "$(hits '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]{1,3}\.')" "0"
262+check "no internal hostnames" "$(hits 'INTERNAL_HOST_A|INTERNAL_HOST_B|INTERNAL_HOST_C')" "0"
263+
264+echo "== worktree hygiene"
265+not_has "no Content-Length in C source" "$ROOT/src/plugin_tetris_3d.c" 'Content-Length'
266+has "stdin guarded by CONTENT_LENGTH" "$ROOT/src/plugin_tetris_3d.c" 'CONTENT_LENGTH'
267+has "require_node_auth present" "$ROOT/src/plugin_tetris_3d.c" 'require_node_auth'
268+has "three credential forms: query" "$ROOT/src/plugin_tetris_3d.c" 'get_query_val(qs, "pwd"'
269+has "three credential forms: header" "$ROOT/src/plugin_tetris_3d.c" 'HTTP_X_BOT_PASSWORD'
270+has "three credential forms: bearer" "$ROOT/src/plugin_tetris_3d.c" 'Bearer '
271+has "win32 branch present" "$ROOT/src/plugin_tetris_3d.c" 'defined(_WIN32)'
272+has "darwin branch present" "$ROOT/src/plugin_tetris_3d.c" '__APPLE__'
273+has "license file is MIT" "$ROOT/LICENSE" 'MIT License'
274+
275+echo "== cross-build artifacts"
276+if [ -f "$ROOT/plugin_tetris_3d.exe" ]; then
277+ check "windows artifact is PE" "$(head -c 2 "$ROOT/plugin_tetris_3d.exe")" "MZ"
278+else
279+ echo " skip windows PE check (not built here)"
280+fi
281+if [ -f "$ROOT/plugin_tetris_3d.musl" ]; then
282+ head -c 4 "$ROOT/plugin_tetris_3d.musl" | od -An -c | grep -q '177 E L F' && ok || bad "musl artifact is ELF"
283+ if grep -qi 'GNU/Linux' "$ROOT/plugin_tetris_3d.musl" 2>/dev/null; then
284+ bad "musl artifact still references glibc"
285+ else
286+ ok
287+ fi
288+else
289+ echo " skip musl ELF check (not built here)"
290+fi
291+if [ -f "$ROOT/plugin_tetris_3d.arm64" ]; then
292+ file "$ROOT/plugin_tetris_3d.arm64" 2>/dev/null | grep -q 'ARM aarch64' && ok || bad "arm64 artifact is aarch64"
293+else
294+ echo " skip arm64 check (not built here)"
295+fi
296+
297+echo "== browser viewport & console (optional)"
298+if [ -x "$ROOT/plugin_tetris_3d" ] && python3 -c 'import playwright' >/dev/null 2>&1; then
299+ python3 "$ROOT/tests/e2e.py" && ok || bad "playwright e2e"
300+else
301+ echo " skip playwright (not installed)"
302+fi
303+
304+echo
305+printf 'passed %d, failed %d\n' "$PASS" "$FAIL"
306+[ "$FAIL" -eq 0 ] || exit 1
307+exit 0
0308
.gitignore+14−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ec3341dindex 0000000..ec3341d
--- /dev/null--- /dev/null
+++ b/.gitignore+++ b/.gitignore
@@ -0,0 +1,14 @@@@ -0,0 +1,14 @@
1+/plugin_tetris_3d
2+/plugin_tetris_3d.musl
3+/plugin_tetris_3d.arm64
4+/plugin_tetris_3d.exe
5+/plugin_tetris_3d.macos-arm64
6+/plugin_tetris_3d.macos-x86_64
7+*.o
8+*.obj
9+*.tmp
10+*.log
11+__pycache__/
12+*.pyc
13+*.dSYM
14+bin/
LICENSE+21−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ef80120index 0000000..ef80120
--- /dev/null--- /dev/null
+++ b/LICENSE+++ b/LICENSE
@@ -0,0 +1,21 @@@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+69−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..59f1c9dindex 0000000..59f1c9d
--- /dev/null--- /dev/null
+++ b/Makefile+++ b/Makefile
@@ -0,0 +1,69 @@@@ -0,0 +1,69 @@
1+# plugin_tetris_3d - ScorpioX Bot open-source 3D block game
2+#
3+# Targets:
4+# make native build -> ./plugin_tetris_3d
5+# make musl static musl x86_64 -> ./plugin_tetris_3d.musl
6+# make arm64 static aarch64 -> ./plugin_tetris_3d.arm64
7+# make win64 MinGW-w64 static PE -> ./plugin_tetris_3d.exe
8+# make macos Apple clang (run on macOS)
9+# make test build + run tests/run.sh
10+# make clean
11+
12+CC ?= cc
13+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings
14+MUSL_CC ?= musl-gcc
15+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
16+ARM_CC ?= aarch64-linux-gnu-gcc
17+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
18+WIN_CC ?= x86_64-w64-mingw32-gcc
19+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
20+SRC := src/plugin_tetris_3d.c
21+BIN := plugin_tetris_3d
22+EXE := plugin_tetris_3d.exe
23+PREFIX ?= $(HOME)/.scorpiox/plugins
24+
25+.PHONY: all native musl arm64 win64 macos install test clean help
26+
27+all: native
28+
29+native: $(BIN)
30+
31+$(BIN): $(SRC) src/ui_html.h
32+ @echo "==> native build ($(CC))"
33+ $(CC) $(CFLAGS) -o $(BIN) $(SRC)
34+
35+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
36+musl: $(SRC) src/ui_html.h
37+ @echo "==> static musl build ($(MUSL_CC))"
38+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC)
39+
40+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
41+arm64: $(SRC) src/ui_html.h
42+ @echo "==> static arm64 build ($(ARM_CC))"
43+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC)
44+
45+# Native Win64 static PE - runs on any Windows 10/11 x64 node
46+win64: $(SRC) src/ui_html.h
47+ @echo "==> MinGW-w64 build ($(WIN_CC))"
48+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC)
49+
50+# Apple clang build (run this on macOS)
51+macos: $(SRC) src/ui_html.h
52+ @echo "==> Apple clang build"
53+ $(CC) -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o $(BIN) $(SRC)
54+
55+install: native
56+ @echo "==> install to $(PREFIX)"
57+ mkdir -p "$(PREFIX)"
58+ cp $(BIN) "$(PREFIX)/"
59+ chmod +x "$(PREFIX)/$(BIN)"
60+
61+test: native
62+ @sh tests/run.sh
63+
64+clean:
65+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64
66+ rm -rf bin
67+
68+help:
69+ @echo "make | make musl | make arm64 | make win64 | make macos | make install | make test | make clean"
README.md+142−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..b6e21aaindex 0000000..b6e21aa
--- /dev/null--- /dev/null
+++ b/README.md+++ b/README.md
@@ -0,0 +1,142 @@@@ -0,0 +1,142 @@
1+# plugin_tetris_3d
2+
3+A 3D block-stacking puzzle game for a ScorpioX Bot node — a single clean-room C99
4+binary, MIT licensed, with no dependency beyond libc.
5+
6+It serves a complete game UI: isometric cubes with real depth and shading,
7+ghost piece, next-piece preview, hold queue, keyboard and touch controls, and a
8+local high-score table. Everything is rendered by a small software 3D projector
9+onto a 2D canvas, so there is no WebGL requirement, no CDN script, and no
10+network request of any kind — the UI works on an offline node.
11+
12+## What it writes
13+
14+One small JSON file, and nothing else:
15+
16+```
17+<plugin dir>/.tetris_scores.json {"scores":[1200,900,300]}
18+```
19+
20+`<plugin dir>` is `$BOT_PLUGIN_DIR` when set, otherwise
21+`%LOCALAPPDATA%\scorpiox\plugins` on Windows and `~/.scorpiox/plugins`
22+(`/workspace/.scorpiox/plugins` on BotCloud) on POSIX. `SX_TETRIS_SCORES`
23+overrides the full path, which is what the test suite uses.
24+
25+The file holds the best ten scores, newest-best first. Writes are atomic at the
26+plugin level: the whole table is re-serialised on each accepted score, so a
27+truncated file can never leave a half-written entry.
28+
29+## Three modes
30+
31+### 1. Discovery
32+
33+```sh
34+./plugin_tetris_3d --meta
35+# {"name":"tetris","desc":"3D block game"}
36+```
37+
38+`SX_PLUGIN_META=1` does the same. This route stays unauthenticated so `/plugins`
39+discovery works.
40+
41+### 2. JSON API
42+
43+```sh
44+./plugin_tetris_3d '?action=scores'
45+./plugin_tetris_3d '?action=save_score&val=1200'
46+curl -d 'val=9900' 'http://node:8150/plugin_tetris_3d?action=save_score'
47+```
48+
49+```json
50+{"ok":true,"plugin":"plugin_tetris_3d","version":"1.0.0",
51+ "highscore":1200,"scores":[1200,900,300]}
52+```
53+
54+`action=scores` (aliases `highscore`, `leaderboard`) reads the table.
55+`action=save_score` inserts a score and returns the updated table; a value that
56+is not a positive integer is refused with `{"ok":false,"error":"invalid_score"}`.
57+Any `POST` whose body carries `val=` or `score=` is treated as a save, and
58+`?format=json` returns the table. If the score file cannot be written the
59+response is `{"ok":false,"error":"score_store_unwritable", ...}` rather than a
60+silent success.
61+
62+The API is gated by `require_node_auth()` exactly like every other node plugin:
63+`X-Bot-Password`, `Authorization: Bearer <pwd>`, or `?pwd=` are all accepted, and
64+the process 401s only when `BOT_PASSWORD` is set and none of the three match.
65+`--meta` stays unauthenticated.
66+
67+### 3. HTML UI
68+
69+A `GET` without an action serves the game in a single self-contained document.
70+`?embed=1` drops the outer chrome so it fits the Chat floating window; the layout
71+is fluid down to a 390 px viewport and short heights.
72+
73+Controls:
74+
75+| Input | Action |
76+|---|---|
77+| Left / Right or `A` / `D` | move |
78+| Up or `W` / `X` | rotate clockwise |
79+| `Z` | rotate counter-clockwise |
80+| Down or `S` | soft drop |
81+| Space | hard drop |
82+| `C` | hold |
83+| `P` / `Esc` | pause |
84+| swipe left / right on the board | move (touch) |
85+| tap the board | rotate (touch) |
86+
87+Scoring is single 100, double 300, triple 500, tetris 800, multiplied by the
88+level; soft drop scores 1 per row and hard drop 2 per row. Level rises every ten
89+lines and the gravity interval tightens from 800 ms toward a 90 ms floor.
90+
91+## Build
92+
93+```sh
94+make # native
95+make musl # static musl x86_64, the universal Linux artifact
96+make arm64 # static aarch64
97+make win64 # static Win64 PE via MinGW-w64
98+make macos # Apple clang, run this on macOS
99+make test # build and run the offline assertion suite
100+```
101+
102+On Windows:
103+
104+```powershell
105+powershell -ExecutionPolicy Bypass -File build.ps1
106+```
107+
108+`src/ui_html.h` is generated from the single-file UI template and is committed,
109+so no generator step is needed to build.
110+
111+## Install on a node
112+
113+```sh
114+make && make install PREFIX=$HOME/.scorpiox/plugins
115+```
116+
117+Or through the node installer once published:
118+
119+```sh
120+curl -X POST 'http://127.0.0.1:8150/plugin_manage?action=install' \
121+ -H "X-Bot-Password: $BOT_PASSWORD" \
122+ -d '{"slug":"tetris-3d","id":"plugin_tetris_3d","mode":"prebuilt","version":"1.0.0"}'
123+```
124+
125+## Tests
126+
127+```sh
128+sh tests/run.sh # 114 offline assertions, no network, no real score file
129+python3 tests/e2e.py # Playwright: 1440 / 1024 / 390 viewports, dark + light
130+```
131+
132+The offline suite covers metadata shape, the score store (ordering, the ten-entry
133+cap, unwritable store, percent-decoded and POST bodies), all three credential
134+forms, the full HTML contract, an emoji audit, and a full-git-history scan for
135+tokens and private addresses. The Playwright run asserts no horizontal or
136+vertical overflow at any viewport, that all three canvases have backing pixels
137+and actually painted, that the HUD renders, that a hard drop moves the score, and
138+that the touch pad is reachable at 390 px.
139+
140+## License
141+
142+MIT. Copyright (c) 2026 SCORPIOX INC.
build.ps1+47−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..babc475index 0000000..babc475
--- /dev/null--- /dev/null
+++ b/build.ps1+++ b/build.ps1
@@ -0,0 +1,47 @@@@ -0,0 +1,47 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_tetris_3d
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_tetris_3d.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin).
8+
9+$ErrorActionPreference = "Stop"
10+$ScriptDir = $PSScriptRoot
11+Push-Location $ScriptDir
12+try {
13+ $Src = Join-Path $ScriptDir "src\plugin_tetris_3d.c"
14+ $Hdr = Join-Path $ScriptDir "src\ui_html.h"
15+ $Out = Join-Path $ScriptDir "plugin_tetris_3d.exe"
16+ $Cc = "x86_64-w64-mingw32-gcc"
17+
18+ if (-not (Test-Path $Src)) { throw "source not found: $Src" }
19+ if (-not (Test-Path $Hdr)) { throw "generated UI header not found: $Hdr" }
20+
21+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
22+ $Candidate = $null
23+ if (Get-Command $Cc -ErrorAction SilentlyContinue) {
24+ $Candidate = $Cc
25+ } elseif (Test-Path "C:\gcc16\bin\gcc.exe") {
26+ $Candidate = "C:\gcc16\bin\gcc.exe"
27+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
28+ $Candidate = "gcc"
29+ }
30+ if (-not $Candidate) { throw "no C compiler found (need x86_64-w64-mingw32-gcc, C:\gcc16\bin\gcc.exe or gcc on PATH)" }
31+
32+ Write-Host "Compiling plugin_tetris_3d.exe with $Candidate ..."
33+ & $Candidate -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o $Out $Src
34+ if ($LASTEXITCODE -ne 0) { throw "compile failed with exit code $LASTEXITCODE" }
35+
36+ $bytes = [System.IO.File]::ReadAllBytes($Out)
37+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
38+ throw "produced artifact is not a PE (no MZ magic)"
39+ }
40+
41+ Write-Host ("Built plugin_tetris_3d.exe {0} bytes" -f $bytes.Length)
42+ & $Out --meta
43+ if ($LASTEXITCODE -ne 0) { throw "--meta smoke test failed" }
44+}
45+finally {
46+ Pop-Location
47+}
plugin.json+12−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..5742df5index 0000000..5742df5
--- /dev/null--- /dev/null
+++ b/plugin.json+++ b/plugin.json
@@ -0,0 +1,12 @@@@ -0,0 +1,12 @@
1+{
2+ "slug": "tetris-3d",
3+ "id": "plugin_tetris_3d",
4+ "title": "3D Block Puzzle Game",
5+ "summary": "Zero-dependency isometric 3D block-stacking puzzle that runs in the ScorpioX Bot Chat floating window or a standalone browser tab. Software-projected cubes on a canvas with ghost piece, next-piece preview, hold queue, keyboard and touch controls, dark and light themes, and local high-score persistence through the node plugin API. No WebGL, no CDN, no network requests.",
6+ "category": "utilities",
7+ "license": "MIT",
8+ "capabilities": ["local_filesystem_write"],
9+ "trust_notice": "Executes native C code on your node. Writes one small JSON file holding your local high scores inside the node plugin directory; it makes zero network requests and reads nothing else.",
10+ "author": "SCORPIOX INC",
11+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-tetris-3d"
12+}
release-dist.sh+364−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..c7883bfindex 0000000..c7883bf
--- /dev/null--- /dev/null
+++ b/release-dist.sh+++ b/release-dist.sh
@@ -0,0 +1,364 @@@@ -0,0 +1,364 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_tetris_3d to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI.
7+# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz ->
8+# manifest.json + SHA256SUMS -> upload -> latest.json / index.json.
9+#
10+# Nothing here contains a host address or a credential. Everything environment-specific
11+# comes from the environment, so this file stays safe to publish:
12+#
13+# DIST_HOST ssh target for the dist server (required for upload)
14+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
15+# DIST_PATH remote web root of the dist server (default /data/dist)
16+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
17+# MAC_USER / MAC_PASS (optional)
18+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
19+# PLUGINGIT_REMOTE public mirror URL to push into
20+#
21+# Usage:
22+# ./release-dist.sh # full release
23+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
24+# ./release-dist.sh --no-macos # skip the macOS legs
25+# ./release-dist.sh --no-mirror # skip the plugingit mirror
26+# ./release-dist.sh --standalone # use this script even if the CLI is installed
27+# # (needed for plugins that link extra Win32 libs,
28+# # which the CLI's fixed link line cannot express)
29+
30+set -euo pipefail
31+
32+SLUG="tetris-3d"
33+ID="plugin_tetris_3d"
34+VERSION="1.0.0"
35+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
36+
37+ROOT="$(cd "$(dirname "$0")" && pwd)"
38+cd "$ROOT"
39+
40+DRY_RUN=0
41+DO_MACOS=1
42+DO_MIRROR=1
43+STANDALONE=0
44+for arg in "$@"; do
45+ case "$arg" in
46+ --standalone) STANDALONE=1 ;;
47+ --dry-run) DRY_RUN=1 ;;
48+ --no-macos) DO_MACOS=0 ;;
49+ --no-mirror) DO_MIRROR=0 ;;
50+ -h|--help) sed -n '2,32p' "$0"; exit 0 ;;
51+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
52+ esac
53+done
54+
55+DIST_HOST="${DIST_HOST:-}"
56+DIST_PASS="${DIST_PASS:-}"
57+DIST_PATH="${DIST_PATH:-/data/dist}"
58+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
59+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
60+
61+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
62+mkdir -p "$STAGE"
63+trap 'rm -rf "$STAGE"' EXIT
64+
65+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
66+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
67+
68+# ---------------------------------------------------------------- 0. preflight
69+say "0/7 preflight"
70+
71+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
72+ say "using scorpiox-cli-botplugin publish"
73+ exec scorpiox-cli-botplugin publish "$ROOT"
74+fi
75+echo " running the standalone pipeline"
76+
77+[ -n "$(git status --porcelain 2>/dev/null)" ] && \
78+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
79+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
80+echo " version $VERSION"
81+echo " commit $COMMIT"
82+
83+# ---------------------------------------------------------------- 1. secret scan
84+say "1/7 secret & LAN scan (full history)"
85+
86+SCAN_TMP="$STAGE/history.txt"
87+# Scan every added/removed line of every commit. Two exclusions, both about the
88+# audit rather than the code: the committer identity line, and any line that is
89+# itself a scan definition - otherwise this file's own detector patterns read as
90+# findings in every historical revision of it.
91+git log -p --all 2>/dev/null \
92+ | grep -v '^Author: ' \
93+ | grep -vE 'scan "|audit "|HITS=|grep -E|P_ROOT=|P_WT=|PK="|\$ALL' \
94+ > "$SCAN_TMP" || : > "$SCAN_TMP"
95+HITS=0
96+scan() { # scan <label> <regex>
97+ local out
98+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
99+ if [ -n "$out" ]; then
100+ printf ' \033[31mHIT\033[0m %s\n' "$1"
101+ printf '%s\n' "$out" | sed 's/^/ /'
102+ HITS=$((HITS + 1))
103+ else
104+ printf ' ok %s\n' "$1"
105+ fi
106+}
107+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
108+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
109+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
110+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
111+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
112+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
113+scan "hard-coded ssh password" 'sshpass -p [^"$]'
114+P_ROOT="/codebases"
115+P_PICOBOT="${P_ROOT}/pico""bot"
116+P_WT=".work""trees"
117+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
118+scan "run-token env assignment" 'RUNNER_'"PASS="
119+if [ "$HITS" -ne 0 ]; then
120+ die "secret scan found $HITS problem(s) - refusing to publish"
121+fi
122+echo " clean: 0 hits"
123+
124+# ---------------------------------------------------------------- 2. build
125+say "2/7 build targets"
126+
127+# linux-x86_64 (glibc, native)
128+if command -v cc >/dev/null 2>&1; then
129+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed"
130+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
131+else
132+ die "no native cc found"
133+fi
134+
135+# linux-x86_64-musl (fully static - the universal Linux artifact)
136+if command -v musl-gcc >/dev/null 2>&1; then
137+ musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c \
138+ || die "musl build failed"
139+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
140+else
141+ echo " skip linux-x86_64-musl (no musl-gcc)"
142+fi
143+
144+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers)
145+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
146+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c \
147+ || die "arm64 build failed"
148+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
149+else
150+ echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)"
151+fi
152+
153+# windows-x86_64 (static PE)
154+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
155+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \
156+ -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed"
157+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
158+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
159+else
160+ echo " skip windows-x86_64 (no MinGW cross compiler)"
161+fi
162+
163+# macOS legs - Mach-O must be produced by Apple clang on a real Mac.
164+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
165+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
166+ MAC_USER="${MAC_USER:-$(whoami)}"
167+ MAC_DIR="/tmp/${ID}-mac-$$"
168+ echo " building macOS legs on $MAC_HOST"
169+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
170+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
171+ if [ -n "${MAC_PASS:-}" ]; then
172+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
173+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
174+ fi
175+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
176+ tar -czf "$STAGE/src.tgz" src
177+ if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \
178+ && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then
179+ # Build straight from the uploaded file - no src/ tree on the remote.
180+ for slice in arm64 x86_64; do
181+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
182+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c" \
183+ 2>/dev/null; then
184+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
185+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
186+ else
187+ echo " warn: macos-$slice build failed on $MAC_HOST"
188+ fi
189+ done
190+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true
191+ else
192+ echo " warn: could not upload source to $MAC_HOST"
193+ fi
194+ else
195+ echo " warn: cannot reach macOS builder $MAC_HOST"
196+ fi
197+else
198+ echo " skip macOS legs (no MAC_HOST or --no-macos)"
199+fi
200+
201+# ---------------------------------------------------------------- 3. manifest
202+say "3/7 manifest + checksums"
203+
204+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
205+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
206+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
207+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
208+
209+target_meta() { # target_meta <key> <file> <format> <relpath>
210+ local key="$1" file="$2" fmt="$3" rel="$4"
211+ [ -f "$file" ] || return 0
212+ local sha size
213+ sha=$(sha256sum "$file" | awk '{print $1}')
214+ size=$(wc -c < "$file" | tr -d ' ')
215+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
216+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
217+}
218+
219+{
220+ printf '{\n'
221+ printf ' "slug": "%s",\n' "$SLUG"
222+ printf ' "id": "%s",\n' "$ID"
223+ printf ' "name": "tetris",\n'
224+ printf ' "desc": "3D block game",\n'
225+ printf ' "title": "3D Block Puzzle Game",\n'
226+ printf ' "summary": "Zero-dependency isometric 3D block-stacking puzzle that runs in the ScorpioX Bot Chat floating window or a standalone browser tab. Software-projected cubes on a canvas with ghost piece, next-piece preview, hold queue, keyboard and touch controls, dark and light themes, and local high-score persistence through the node plugin API. No WebGL, no CDN, no network requests.",\n'
227+ printf ' "category": "utilities",\n'
228+ printf ' "version": "%s",\n' "$VERSION"
229+ printf ' "license": "MIT",\n'
230+ printf ' "trust_notice": "Executes native C code on your node. Writes one small JSON file holding your local high scores inside the node plugin directory; it makes zero network requests and reads nothing else.",\n'
231+ printf ' "capabilities": ["local_filesystem_write"],\n'
232+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
233+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
234+ printf ' "git_commit": "%s",\n' "$COMMIT"
235+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
236+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
237+ printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID"
238+ printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID"
239+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
240+ printf ' "targets": {\n'
241+ first=1
242+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
243+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
244+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
245+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
246+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
247+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
248+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
249+ printf '\n }\n}\n'
250+} > "$STAGE/manifest.json"
251+
252+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
253+ || die "generated manifest.json is not valid JSON"
254+echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)"
255+
256+# SHA256SUMS - relative paths, exactly as published
257+( cd "$STAGE"
258+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
259+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
260+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
261+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
262+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
263+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
264+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
265+ true ) > "$STAGE/SHA256SUMS"
266+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
267+
268+# ---------------------------------------------------------------- 4. stage
269+say "4/7 stage tree"
270+PKG="$STAGE/pkg"
271+mkdir -p "$PKG"
272+cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
273+[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; }
274+[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; }
275+[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; }
276+[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; }
277+[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; }
278+[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; }
279+echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)"
280+
281+if [ "$DRY_RUN" -eq 1 ]; then
282+ say "dry run - leaving the staging tree in $PKG"
283+ trap - EXIT
284+ exit 0
285+fi
286+
287+# ---------------------------------------------------------------- 5. upload
288+say "5/7 upload to the dist server"
289+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)"
290+SSH=(ssh -o StrictHostKeyChecking=no)
291+SCP=(scp -o StrictHostKeyChecking=no)
292+if [ -n "$DIST_PASS" ]; then
293+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
294+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
295+fi
296+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
297+
298+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
299+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
300+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
301+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
302+# OpenSSH 9 refuses to scp a bare "." source.
303+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
304+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
305+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
306+ || die "remote extract failed"
307+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
308+
309+# latest.json = copy of this version's manifest
310+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
311+ || die "latest.json update failed"
312+echo " updated bot-plugins/$SLUG/latest.json"
313+
314+# index.json - merge, preserving every sibling <slug>/latest.json
315+say "index.json merge"
316+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
317+import json, os, sys, glob
318+slug = sys.argv[1]
319+entries = {}
320+for p in sorted(glob.glob('*/latest.json')):
321+ s = os.path.dirname(p)
322+ try:
323+ entries[s] = json.load(open(p))
324+ except Exception:
325+ pass
326+index = {
327+ 'ok': True,
328+ 'service': 'bot-plugins-dist',
329+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
330+ 'count': len(entries),
331+ 'slugs': sorted(entries),
332+ 'plugins': [entries[k] for k in sorted(entries)],
333+}
334+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
335+os.replace('index.json.tmp', 'index.json')
336+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
337+PY" || die "index.json merge failed"
338+
339+# ---------------------------------------------------------------- 6. mirror
340+say "6/7 plugingit mirror"
341+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
342+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
343+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|")
344+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
345+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
346+ echo " mirrored to $PLUGINGIT_REMOTE"
347+else
348+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
349+fi
350+
351+# ---------------------------------------------------------------- 7. verify
352+say "7/7 verify"
353+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
354+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
355+if [ "$CODE" = "200" ]; then
356+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \
357+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
358+else
359+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
360+fi
361+
362+printf '\n\033[1mrelease complete\033[0m\n'
363+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
364+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/plugin_tetris_3d.c+458−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..00a217dindex 0000000..00a217d
--- /dev/null--- /dev/null
+++ b/src/plugin_tetris_3d.c+++ b/src/plugin_tetris_3d.c
@@ -0,0 +1,458 @@@@ -0,0 +1,458 @@
1+/*
2+ * plugin_tetris_3d - ScorpioX Bot open-source 3D block game (clean room)
3+ *
4+ * A single dependency-free C99 binary that serves THREE modes:
5+ * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
6+ * 2. ?action=scores | ?action=save_score | ?format=json -> JSON node API
7+ * 3. GET (default) -> self-contained HTML game UI
8+ *
9+ * The game itself is a 3D block-stacking puzzle rendered by a small software
10+ * 3D projector onto a 2D canvas. There is no WebGL requirement, no CDN, no
11+ * third-party JavaScript and no runtime library beyond libc, so the UI works
12+ * offline on every node and produces zero network requests.
13+ *
14+ * High scores are stored locally in a small JSON file inside the node plugin
15+ * directory:
16+ * POSIX ~/.scorpiox/plugins/.tetris_scores.json
17+ * ($BOT_PLUGIN_DIR when set, /workspace/.scorpiox/plugins on BotCloud)
18+ * Windows %LOCALAPPDATA%\scorpiox\plugins\.tetris_scores.json
19+ * override SX_TETRIS_SCORES (full path, used by the test suite)
20+ *
21+ * Nothing else is read or written. There is no parameter anywhere in this
22+ * file that can point it at another host.
23+ *
24+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
25+ */
26+
27+#if defined(_WIN32) && !defined(_WIN32_WINNT)
28+# define _WIN32_WINNT 0x0601
29+#endif
30+
31+#if !defined(_WIN32)
32+# define _POSIX_C_SOURCE 200809L
33+# define _DEFAULT_SOURCE 1
34+# if defined(__APPLE__)
35+# define _DARWIN_C_SOURCE 1
36+# endif
37+#endif
38+
39+#include <stdio.h>
40+#include <stdlib.h>
41+#include <string.h>
42+#include <ctype.h>
43+#include <time.h>
44+#include <errno.h>
45+
46+#if defined(_WIN32)
47+# define WIN32_LEAN_AND_MEAN
48+# include <windows.h>
49+# include <direct.h>
50+# define SX_SEP '\\'
51+#else
52+# include <unistd.h>
53+# include <sys/stat.h>
54+# include <sys/types.h>
55+# define SX_SEP '/'
56+#endif
57+
58+#define PLUGIN_SLUG "tetris-3d"
59+#define PLUGIN_ID "plugin_tetris_3d"
60+#define PLUGIN_NAME "tetris"
61+#define PLUGIN_DESC "3D block game"
62+#define PLUGIN_VER "1.0.0"
63+
64+#define MAX_SCORES 10
65+#define PATH_SZ 1024
66+#define BODY_SZ 2048
67+
68+/* ------------------------------------------------------------------ */
69+/* Small string helpers */
70+/* ------------------------------------------------------------------ */
71+
72+static void str_copy(char *dst, size_t sz, const char *src)
73+{
74+ size_t i = 0;
75+ if (!dst || sz == 0) return;
76+ if (!src) { dst[0] = '\0'; return; }
77+ while (i + 1 < sz && src[i]) { dst[i] = src[i]; i++; }
78+ dst[i] = '\0';
79+}
80+
81+static void url_decode(char *s)
82+{
83+ char *o = s;
84+ if (!s) return;
85+ while (*s) {
86+ if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
87+ int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
88+ int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
89+ *o++ = (char)((hi << 4) | lo);
90+ s += 3;
91+ } else if (*s == '+') {
92+ *o++ = ' ';
93+ s++;
94+ } else {
95+ *o++ = *s++;
96+ }
97+ }
98+ *o = '\0';
99+}
100+
101+/* Read one query/body parameter, percent-decoded. Returns 1 when present. */
102+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
103+{
104+ size_t klen;
105+ const char *p;
106+
107+ if (!out || outsz == 0) return 0;
108+ out[0] = '\0';
109+ if (!qs || !key) return 0;
110+ klen = strlen(key);
111+
112+ for (p = qs; *p; ) {
113+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
114+ const char *v = p + klen + 1;
115+ size_t i = 0;
116+ while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++;
117+ out[i] = '\0';
118+ url_decode(out);
119+ return 1;
120+ }
121+ p = strchr(p, '&');
122+ if (!p) break;
123+ p++;
124+ }
125+ return 0;
126+}
127+
128+/* ------------------------------------------------------------------ */
129+/* Node security */
130+/* ------------------------------------------------------------------ */
131+
132+/* Accept X-Bot-Password, Authorization: Bearer <pwd> or ?pwd=. The bot web
133+ * frontend appends ?pwd= for iframes, so all three forms must work. When
134+ * BOT_PASSWORD is unset the node is unauthenticated by configuration and the
135+ * check is a no-op. --meta stays unauthenticated so discovery works. */
136+static void require_node_auth(void)
137+{
138+ const char *np = getenv("BOT_PASSWORD");
139+ const char *xp;
140+ const char *auth;
141+
142+ if (!np || !*np) return;
143+
144+ xp = getenv("HTTP_X_BOT_PASSWORD");
145+ if (xp && strcmp(xp, np) == 0) return;
146+
147+ auth = getenv("HTTP_AUTHORIZATION");
148+ if (auth) {
149+ while (*auth == ' ') auth++;
150+ if (strncmp(auth, "Bearer ", 7) == 0) {
151+ auth += 7;
152+ while (*auth == ' ') auth++;
153+ if (strcmp(auth, np) == 0) return;
154+ }
155+ }
156+
157+ {
158+ char qpwd[256];
159+ const char *qs = getenv("QUERY_STRING");
160+ if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) return;
161+ }
162+
163+ fputs("Status: 401 Unauthorized\r\n"
164+ "Content-Type: application/json; charset=utf-8\r\n"
165+ "Cache-Control: no-store\r\n\r\n"
166+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
167+ exit(0);
168+}
169+
170+/* ------------------------------------------------------------------ */
171+/* Local high-score store */
172+/* ------------------------------------------------------------------ */
173+
174+typedef struct {
175+ long v[MAX_SCORES];
176+ int n;
177+} Scores;
178+
179+static void path_join(char *dst, size_t sz, const char *a, const char *b)
180+{
181+ if (!dst || sz == 0) return;
182+ dst[0] = '\0';
183+ if (!a || !b) return;
184+ if (!*a) { str_copy(dst, sz, b); return; }
185+ str_copy(dst, sz, a);
186+ {
187+ size_t l = strlen(dst);
188+ if (l + 1 < sz) { dst[l] = SX_SEP; dst[l + 1] = '\0'; }
189+ }
190+ {
191+ size_t l = strlen(dst);
192+ size_t i = 0;
193+ while (l + i + 1 < sz && b[i]) { dst[l + i] = b[i]; i++; }
194+ dst[l + i] = '\0';
195+ }
196+}
197+
198+static void mkdir_one(const char *p)
199+{
200+#if defined(_WIN32)
201+ _mkdir(p);
202+#else
203+ mkdir(p, 0700);
204+#endif
205+}
206+
207+/* Resolve <plugin dir>/.tetris_scores.json */
208+static int scores_path(char *out, size_t sz)
209+{
210+ const char *env = getenv("SX_TETRIS_SCORES");
211+ char dir[PATH_SZ];
212+ const char *base;
213+
214+ if (env && *env) { str_copy(out, sz, env); return 1; }
215+
216+ base = getenv("BOT_PLUGIN_DIR");
217+ if (base && *base) {
218+ mkdir_one(base);
219+ dir[0] = '\0';
220+ str_copy(dir, sizeof dir, base);
221+ } else {
222+#if defined(_WIN32)
223+ const char *la = getenv("LOCALAPPDATA");
224+ if (la && *la) {
225+ path_join(dir, sizeof dir, la, "scorpiox");
226+ } else {
227+ const char *up = getenv("USERPROFILE");
228+ if (up && *up) {
229+ path_join(dir, sizeof dir, up, ".scorpiox");
230+ } else {
231+ str_copy(dir, sizeof dir, ".");
232+ }
233+ }
234+ mkdir_one(dir);
235+ {
236+ char tmp[PATH_SZ];
237+ path_join(tmp, sizeof tmp, dir, "plugins");
238+ str_copy(dir, sizeof dir, tmp);
239+ mkdir_one(dir);
240+ }
241+#else
242+ const char *home = getenv("HOME");
243+# if defined(__APPLE__)
244+ if (access("/workspace", W_OK) == 0) {
245+ path_join(dir, sizeof dir, "/workspace/.scorpiox", "plugins");
246+ } else
247+# endif
248+ if (home && *home) {
249+ path_join(dir, sizeof dir, home, ".scorpiox");
250+ mkdir_one(dir);
251+ {
252+ char tmp[PATH_SZ];
253+ path_join(tmp, sizeof tmp, dir, "plugins");
254+ str_copy(dir, sizeof dir, tmp);
255+ }
256+ mkdir_one(dir);
257+ } else {
258+ str_copy(dir, sizeof dir, ".");
259+ }
260+#endif
261+ }
262+ path_join(out, sz, dir, ".tetris_scores.json");
263+ return 1;
264+}
265+
266+static void scores_load(Scores *s)
267+{
268+ char path[PATH_SZ];
269+ FILE *fp;
270+ char buf[BODY_SZ];
271+ size_t got;
272+
273+ memset(s, 0, sizeof *s);
274+ if (!scores_path(path, sizeof path)) return;
275+
276+ fp = fopen(path, "rb");
277+ if (!fp) return;
278+ got = fread(buf, 1, sizeof buf - 1, fp);
279+ fclose(fp);
280+ buf[got] = '\0';
281+
282+ {
283+ const char *p = strstr(buf, "\"scores\"");
284+ if (!p) p = buf;
285+ p = strchr(p, '[');
286+ if (!p) return;
287+ p++;
288+ while (*p && s->n < MAX_SCORES) {
289+ while (*p && !isdigit((unsigned char)*p) && *p != ']') p++;
290+ if (!*p || *p == ']') break;
291+ {
292+ long v = strtol(p, NULL, 10);
293+ if (v > 0) s->v[s->n++] = v;
294+ while (*p && *p != ',' && *p != ']') p++;
295+ if (*p == ',') p++;
296+ }
297+ }
298+ }
299+}
300+
301+static int scores_save(const Scores *s)
302+{
303+ char path[PATH_SZ];
304+ FILE *fp;
305+ int i;
306+
307+ if (!scores_path(path, sizeof path)) return 0;
308+ fp = fopen(path, "wb");
309+ if (!fp) return 0;
310+ fputs("{\"scores\":[", fp);
311+ for (i = 0; i < s->n; i++) {
312+ if (i) fputc(',', fp);
313+ fprintf(fp, "%ld", s->v[i]);
314+ }
315+ fputs("]}\n", fp);
316+ fclose(fp);
317+ return 1;
318+}
319+
320+static void scores_add(Scores *s, long val)
321+{
322+ int i, pos;
323+ if (val <= 0) return;
324+ if (s->n < MAX_SCORES) {
325+ pos = s->n++;
326+ } else {
327+ if (val <= s->v[MAX_SCORES - 1]) return;
328+ pos = MAX_SCORES - 1;
329+ }
330+ for (i = pos; i > 0 && s->v[i - 1] < val; i--) s->v[i] = s->v[i - 1];
331+ s->v[i] = val;
332+}
333+
334+static void scores_print_json(const Scores *s)
335+{
336+ int i;
337+ printf("{\"ok\":true,\"plugin\":\"%s\",\"version\":\"%s\",\"highscore\":%ld,\"scores\":[",
338+ PLUGIN_ID, PLUGIN_VER, s->n ? s->v[0] : 0L);
339+ for (i = 0; i < s->n; i++) {
340+ if (i) fputc(',', stdout);
341+ printf("%ld", s->v[i]);
342+ }
343+ fputs("]}\n", stdout);
344+}
345+
346+/* Read the POST body when the frontend actually sent one. Guarded on
347+ * CONTENT_LENGTH so an inherited empty stdin never blocks the process. */
348+static int read_body(char *out, size_t sz)
349+{
350+ const char *cl = getenv("CONTENT_LENGTH");
351+ long len;
352+ size_t got;
353+
354+ if (!out || sz == 0) return 0;
355+ out[0] = '\0';
356+ if (!cl || !*cl) return 0;
357+ len = strtol(cl, NULL, 10);
358+ if (len <= 0) return 0;
359+ if ((size_t)len > sz - 1) len = (long)sz - 1;
360+ got = fread(out, 1, (size_t)len, stdin);
361+ out[got] = '\0';
362+ return (int)got;
363+}
364+
365+/* ------------------------------------------------------------------ */
366+/* Modes */
367+/* ------------------------------------------------------------------ */
368+
369+#include "ui_html.h"
370+
371+static const char *method(void)
372+{
373+ const char *m = getenv("REQUEST_METHOD");
374+ return (m && *m) ? m : "GET";
375+}
376+
377+int main(int argc, char **argv)
378+{
379+ const char *qs;
380+ char action[64];
381+ char valstr[64];
382+ char body[BODY_SZ];
383+ Scores scores;
384+
385+ /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */
386+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
387+ printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC);
388+ return 0;
389+ }
390+ if (argc > 1 && strcmp(argv[1], "--version") == 0) {
391+ printf("%s %s\n", PLUGIN_ID, PLUGIN_VER);
392+ return 0;
393+ }
394+
395+ require_node_auth();
396+ qs = getenv("QUERY_STRING");
397+ if (!qs) qs = "";
398+
399+ action[0] = '\0';
400+ valstr[0] = '\0';
401+ get_query_val(qs, "action", action, sizeof action);
402+
403+ /* 2. JSON API: ?action=..., ?format=json, or any POST with a body */
404+ if (action[0] || strstr(qs, "format=json") || strncmp(method(), "POST", 4) == 0) {
405+ char format[32];
406+ format[0] = '\0';
407+ get_query_val(qs, "format", format, sizeof format);
408+
409+ if (!action[0] && strncmp(method(), "POST", 4) == 0) str_copy(action, sizeof action, "save_score");
410+ if (!action[0]) str_copy(action, sizeof action, "scores");
411+
412+ read_body(body, sizeof body);
413+ if (!get_query_val(qs, "val", valstr, sizeof valstr) && body[0]) {
414+ if (!get_query_val(body, "val", valstr, sizeof valstr))
415+ (void)get_query_val(body, "score", valstr, sizeof valstr);
416+ }
417+ if (!valstr[0]) get_query_val(qs, "score", valstr, sizeof valstr);
418+ if (!valstr[0] && body[0]) {
419+ /* a bare numeric body is accepted too */
420+ const char *p = body;
421+ while (*p && !isdigit((unsigned char)*p) && *p != '-') p++;
422+ if (*p) str_copy(valstr, sizeof valstr, p);
423+ }
424+
425+ scores_load(&scores);
426+
427+ fputs("Content-Type: application/json; charset=utf-8\r\n"
428+ "Cache-Control: no-store\r\n\r\n", stdout);
429+
430+ if (strcmp(action, "save_score") == 0) {
431+ long v = strtol(valstr, NULL, 10);
432+ if (v > 0) {
433+ scores_add(&scores, v);
434+ if (!scores_save(&scores))
435+ printf("{\"ok\":false,\"error\":\"score_store_unwritable\",\"highscore\":%ld}\n",
436+ scores.n ? scores.v[0] : 0L);
437+ else
438+ scores_print_json(&scores);
439+ } else {
440+ printf("{\"ok\":false,\"error\":\"invalid_score\"}\n");
441+ }
442+ return 0;
443+ }
444+ if (strcmp(action, "scores") == 0 || strcmp(action, "highscore") == 0 ||
445+ strcmp(action, "leaderboard") == 0) {
446+ scores_print_json(&scores);
447+ return 0;
448+ }
449+ printf("{\"ok\":false,\"error\":\"unknown_action\"}\n");
450+ return 0;
451+ }
452+
453+ /* 3. HTML UI */
454+ fputs("Content-Type: text/html; charset=utf-8\r\n"
455+ "Cache-Control: no-store\r\n\r\n", stdout);
456+ fputs(UI_HTML, stdout);
457+ return 0;
458+}
src/ui_html.h+583−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..0646853index 0000000..0646853
--- /dev/null--- /dev/null
+++ b/src/ui_html.h+++ b/src/ui_html.h
@@ -0,0 +1,583 @@@@ -0,0 +1,583 @@
1+/* Generated from the single-file UI template. Do not edit by hand. */
2+#ifndef SX_TETRIS_UI_HTML_H
3+#define SX_TETRIS_UI_HTML_H
4+
5+static const char *UI_HTML =
6+ "<!DOCTYPE html>\n"
7+ "<html lang=\"en\"><head><meta charset=\"utf-8\">\n"
8+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no\">\n"
9+ "<title>tetris</title>\n"
10+ "<style>\n"
11+ ":root{color-scheme:dark light;--bg:#08080b;--panel:rgba(22,22,28,.72);--panel-solid:#16161c;--text:#f4f4f7;--muted:#9b9ba6;--line:rgba(255,255,255,.11);--accent:#0a84ff;--good:#30d158;--warn:#ff9f0a;--radius:14px}\n"
12+ "@media(prefers-color-scheme:light){:root{--bg:#eceef3;--panel:rgba(255,255,255,.78);--panel-solid:#fff;--text:#14141a;--muted:#5f5f6b;--line:rgba(0,0,0,.1)}}\n"
13+ "html[data-theme=\"dark\"]{--bg:#08080b;--panel:rgba(22,22,28,.72);--panel-solid:#16161c;--text:#f4f4f7;--muted:#9b9ba6;--line:rgba(255,255,255,.11)}\n"
14+ "html[data-theme=\"light\"]{--bg:#eceef3;--panel:rgba(255,255,255,.78);--panel-solid:#fff;--text:#14141a;--muted:#5f5f6b;--line:rgba(0,0,0,.1)}\n"
15+ "*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}\n"
16+ "html,body{margin:0;padding:0;height:100%;overflow:hidden;background:var(--bg);color:var(--text);font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Inter,system-ui,sans-serif}\n"
17+ "#app{position:relative;width:100%;height:100%;display:flex;flex-direction:column}\n"
18+ "#top{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:8px 10px;flex:0 0 auto;z-index:5}\n"
19+ "#title{display:flex;align-items:center;gap:8px;font-size:12px;font-weight:700;letter-spacing:.9px;text-transform:uppercase;color:var(--muted)}\n"
20+ "#dot{width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 10px var(--accent)}\n"
21+ "#topbtns{display:flex;gap:6px}\n"
22+ ".iconbtn{background:var(--panel);border:1px solid var(--line);color:var(--text);border-radius:10px;padding:6px 10px;font-size:11px;font-weight:650;cursor:pointer;backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);font-family:inherit}\n"
23+ ".iconbtn:active{transform:scale(.95)}\n"
24+ "#main{flex:1 1 auto;display:flex;gap:10px;padding:0 10px 10px;min-height:0}\n"
25+ "#stage{position:relative;flex:1 1 auto;min-width:0;border-radius:var(--radius);overflow:hidden;background:radial-gradient(120% 90% at 50% 0%,rgba(10,132,255,.10),transparent 60%),var(--panel);border:1px solid var(--line);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px)}\n"
26+ "#cv{display:block;width:100%;height:100%;touch-action:none}\n"
27+ "#side{flex:0 0 132px;display:flex;flex-direction:column;gap:8px;overflow:hidden}\n"
28+ ".card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:8px 10px;backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px)}\n"
29+ ".lbl{font-size:9px;letter-spacing:.8px;text-transform:uppercase;color:var(--muted);font-weight:700}\n"
30+ ".val{font-variant-numeric:tabular-nums;font-size:19px;font-weight:750;line-height:1.15}\n"
31+ ".val.sm{font-size:12px;font-weight:650}\n"
32+ ".mini{width:100%;height:66px;display:block}\n"
33+ ".mini.tall{height:150px}\n"
34+ "#overlay{position:absolute;inset:0;display:none;align-items:center;justify-content:center;background:rgba(6,6,9,.78);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);z-index:20;padding:16px}\n"
35+ "#overlay.on{display:flex}\n"
36+ "#modal{background:var(--panel-solid);border:1px solid var(--line);border-radius:18px;padding:20px 22px;text-align:center;max-width:300px;width:100%}\n"
37+ "#mTitle{margin:0 0 6px;font-size:20px;font-weight:800;letter-spacing:1.4px}\n"
38+ "#mSub{margin:0 0 14px;font-size:12px;color:var(--muted);line-height:1.5}\n"
39+ "#mBtn{background:var(--accent);color:#fff;border:0;border-radius:999px;padding:11px 26px;font-size:14px;font-weight:750;cursor:pointer;font-family:inherit;width:100%}\n"
40+ "#mBtn:active{transform:scale(.97)}\n"
41+ "#pad{flex:0 0 auto;display:grid;grid-template-columns:repeat(4,1fr);gap:6px;padding:0 10px 10px}\n"
42+ ".pbtn{background:var(--panel);border:1px solid var(--line);color:var(--text);border-radius:12px;padding:12px 0;font-size:15px;font-weight:700;cursor:pointer;font-family:inherit;backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);user-select:none;touch-action:manipulation}\n"
43+ ".pbtn:active{background:var(--accent);color:#fff;transform:scale(.95)}\n"
44+ ".pbtn.wide{grid-column:span 2}\n"
45+ ".pbtn.hi{background:rgba(10,132,255,.18);border-color:rgba(10,132,255,.45);color:#5db0ff}\n"
46+ "html[data-theme=\"light\"] .pbtn.hi{color:#0071e3}\n"
47+ "@media(prefers-color-scheme:light){html:not([data-theme=\"dark\"]) .pbtn.hi{color:#0071e3;background:rgba(0,113,227,.14);border-color:rgba(0,113,227,.42)}}\n"
48+ "@media (max-width:420px){\n"
49+ " #side{flex:0 0 92px}\n"
50+ " .val{font-size:15px}\n"
51+ " .mini{height:52px}\n"
52+ " .mini.tall{height:110px}\n"
53+ " #pad{gap:5px;padding:0 8px 8px}\n"
54+ " .pbtn{padding:10px 0;font-size:14px}\n"
55+ " #main{gap:7px;padding:0 8px 8px}\n"
56+ " #top{padding:7px 8px}\n"
57+ "}\n"
58+ "@media (max-height:560px){\n"
59+ " .mini{height:44px}\n"
60+ " .mini.tall{height:84px}\n"
61+ " #pad{padding-bottom:6px}\n"
62+ " .pbtn{padding:8px 0}\n"
63+ "}\n"
64+ "</style></head>\n"
65+ "<body><div id=\"app\">\n"
66+ "<div id=\"top\">\n"
67+ " <div id=\"title\"><span id=\"dot\"></span><span>3D BLOCKS</span></div>\n"
68+ " <div id=\"topbtns\">\n"
69+ " <button class=\"iconbtn\" id=\"btnTheme\" type=\"button\">Theme</button>\n"
70+ " <button class=\"iconbtn\" id=\"btnRestart\" type=\"button\">Restart</button>\n"
71+ " </div>\n"
72+ "</div>\n"
73+ "<div id=\"main\">\n"
74+ " <div id=\"stage\"><canvas id=\"cv\"></canvas>\n"
75+ " <div id=\"overlay\"><div id=\"modal\">\n"
76+ " <h2 id=\"mTitle\">READY</h2>\n"
77+ " <p id=\"mSub\">Arrows or WASD to move and rotate. Space drops.</p>\n"
78+ " <button id=\"mBtn\" type=\"button\">Start</button>\n"
79+ " </div></div>\n"
80+ " </div>\n"
81+ " <div id=\"side\">\n"
82+ " <div class=\"card\"><div class=\"lbl\">Score</div><div class=\"val\" id=\"vScore\">0</div></div>\n"
83+ " <div class=\"card\"><div class=\"lbl\">Best</div><div class=\"val\" id=\"vBest\">0</div></div>\n"
84+ " <div class=\"card\"><div class=\"lbl\">Lines / Level</div><div class=\"val sm\" id=\"vLines\">0 / 1</div></div>\n"
85+ " <div class=\"card\"><div class=\"lbl\">Next</div><canvas class=\"mini tall\" id=\"cvNext\"></canvas></div>\n"
86+ " <div class=\"card\"><div class=\"lbl\">Hold</div><canvas class=\"mini\" id=\"cvHold\"></canvas></div>\n"
87+ " </div>\n"
88+ "</div>\n"
89+ "<div id=\"pad\">\n"
90+ " <button class=\"pbtn\" id=\"bLeft\" type=\"button\">Left</button>\n"
91+ " <button class=\"pbtn\" id=\"bRot\" type=\"button\">Rotate</button>\n"
92+ " <button class=\"pbtn\" id=\"bRight\" type=\"button\">Right</button>\n"
93+ " <button class=\"pbtn\" id=\"bDown\" type=\"button\">Down</button>\n"
94+ " <button class=\"pbtn wide hi\" id=\"bDrop\" type=\"button\">Hard Drop</button>\n"
95+ " <button class=\"pbtn\" id=\"bHold\" type=\"button\">Hold</button>\n"
96+ " <button class=\"pbtn\" id=\"bPause\" type=\"button\">Pause</button>\n"
97+ "</div>\n"
98+ "</div>\n"
99+ "<script>\n"
100+ "(function(){\n"
101+ "\"use strict\";\n"
102+ "\n"
103+ "var q = new URLSearchParams(location.search);\n"
104+ "var HUB = q.get('plugin') || '';\n"
105+ "var NODE = q.get('node') || '';\n"
106+ "var SID = q.get('id') || '';\n"
107+ "var PWD = q.get('pwd') || (NODE ? (localStorage.getItem('bot_pwd_' + NODE) || '') : (localStorage.getItem('bot_active_pwd') || ''));\n"
108+ "var EMBED = q.get('embed') === '1' || q.get('embed') === 'true';\n"
109+ "\n"
110+ "/* The hub proxies through /plugins?plugin=<id>; a node opened directly serves\n"
111+ " the plugin itself at /plugin_tetris_3d. Calling /plugins?plugin= on a node\n"
112+ " returns the discovery list, not the plugin, so branch on which one we are. */\n"
113+ "function apiUrl(action, extra){\n"
114+ " var base = HUB ? ('/plugins?plugin=' + encodeURIComponent(HUB) + '&action=' + encodeURIComponent(action))\n"
115+ " : ('/plugin_tetris_3d?action=' + encodeURIComponent(action));\n"
116+ " if (extra) base += '&' + extra;\n"
117+ " if (NODE) base += '&node=' + encodeURIComponent(NODE);\n"
118+ " if (SID) base += '&id=' + encodeURIComponent(SID);\n"
119+ " if (PWD) base += '&pwd=' + encodeURIComponent(PWD);\n"
120+ " return base;\n"
121+ "}\n"
122+ "function api(action, extra, opts){\n"
123+ " var o = opts || {};\n"
124+ " if (PWD) o.headers = Object.assign({'X-Bot-Password': PWD}, o.headers || {});\n"
125+ " return fetch(apiUrl(action, extra), o).then(function(r){ return r.json(); });\n"
126+ "}\n"
127+ "\n"
128+ "/* ---------------------------------------------------------------- theme */\n"
129+ "var THEME_KEY = 'sx_tetris_theme';\n"
130+ "function applyTheme(t){\n"
131+ " if (t === 'dark' || t === 'light') document.documentElement.setAttribute('data-theme', t);\n"
132+ " else document.documentElement.removeAttribute('data-theme');\n"
133+ " document.getElementById('btnTheme').textContent =\n"
134+ " (document.documentElement.getAttribute('data-theme') === 'light') ? 'Dark' : 'Light';\n"
135+ "}\n"
136+ "applyTheme(localStorage.getItem(THEME_KEY) || q.get('theme') || '');\n"
137+ "document.getElementById('btnTheme').addEventListener('click', function(){\n"
138+ " var cur = document.documentElement.getAttribute('data-theme');\n"
139+ " if (!cur) cur = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';\n"
140+ " var next = cur === 'light' ? 'dark' : 'light';\n"
141+ " localStorage.setItem(THEME_KEY, next);\n"
142+ " applyTheme(next);\n"
143+ "});\n"
144+ "\n"
145+ "/* ---------------------------------------------------------------- board */\n"
146+ "var COLS = 10, ROWS = 20, DEPTH = 3;\n"
147+ "var SHAPES = [\n"
148+ " { k:'I', c:'#22d3ee', b:[[1,1,1,1]] },\n"
149+ " { k:'J', c:'#3b82f6', b:[[1,0,0],[1,1,1]] },\n"
150+ " { k:'L', c:'#f59e0b', b:[[0,0,1],[1,1,1]] },\n"
151+ " { k:'O', c:'#facc15', b:[[1,1],[1,1]] },\n"
152+ " { k:'S', c:'#22c55e', b:[[0,1,1],[1,1,0]] },\n"
153+ " { k:'T', c:'#a855f7', b:[[0,1,0],[1,1,1]] },\n"
154+ " { k:'Z', c:'#ef4444', b:[[1,1,0],[0,1,1]] }\n"
155+ "];\n"
156+ "\n"
157+ "var grid = []; /* grid[y][x] = color string or 0 */\n"
158+ "var piece = null; /* {c, b, x, y} */\n"
159+ "var nextQueue = [];\n"
160+ "var holdColor = null, holdUsed = false;\n"
161+ "var score = 0, lines = 0, level = 1, best = 0;\n"
162+ "var paused = false, over = false, started = false;\n"
163+ "var dropAcc = 0, dropInterval = 800, lastTs = 0;\n"
164+ "var flash = []; /* {rows:[], t:0} */\n"
165+ "\n"
166+ "for (var gy = 0; gy < ROWS; gy++) { grid[gy] = []; for (var gx = 0; gx < COLS; gx++) grid[gy][gx] = 0; }\n"
167+ "\n"
168+ "function newBag(){\n"
169+ " var bag = SHAPES.slice();\n"
170+ " for (var i = bag.length - 1; i > 0; i--) {\n"
171+ " var j = Math.floor(Math.random() * (i + 1));\n"
172+ " var t = bag[i]; bag[i] = bag[j]; bag[j] = t;\n"
173+ " }\n"
174+ " return bag;\n"
175+ "}\n"
176+ "function refill(){\n"
177+ " while (nextQueue.length < 5) nextQueue = nextQueue.concat(newBag());\n"
178+ "}\n"
179+ "function nextPiece(){\n"
180+ " refill();\n"
181+ " var s = nextQueue.shift();\n"
182+ " refill();\n"
183+ " return s;\n"
184+ "}\n"
185+ "function spawn(){\n"
186+ " var s = nextPiece();\n"
187+ " piece = { c: s.c, b: s.b.map(function(r){ return r.slice(); }),\n"
188+ " x: Math.floor((COLS - s.b[0].length) / 2), y: ROWS - s.b.length };\n"
189+ " holdUsed = false;\n"
190+ " if (collides(piece.x, piece.y, piece.b)) { gameOver(); }\n"
191+ " drawSide();\n"
192+ "}\n"
193+ "\n"
194+ "function collides(px, py, b){\n"
195+ " for (var r = 0; r < b.length; r++) {\n"
196+ " for (var c = 0; c < b[r].length; c++) {\n"
197+ " if (!b[r][c]) continue;\n"
198+ " var nx = px + c, ny = py + r;\n"
199+ " if (nx < 0 || nx >= COLS || ny < 0) return true;\n"
200+ " if (ny < ROWS && grid[ny][nx]) return true;\n"
201+ " }\n"
202+ " }\n"
203+ " return false;\n"
204+ "}\n"
205+ "function rotated(b, dir){\n"
206+ " var h = b.length, w = b[0].length, out = [], r, c;\n"
207+ " if (dir > 0) { for (c = 0; c < w; c++) { out[c] = []; for (r = h - 1; r >= 0; r--) out[c][h - 1 - r] = b[r][c]; } }\n"
208+ " else { for (c = 0; c < w; c++) { out[c] = []; for (r = 0; r < h; r++) out[c][r] = b[r][w - 1 - c]; } }\n"
209+ " return out;\n"
210+ "}\n"
211+ "function tryRotate(dir){\n"
212+ " if (!piece || paused || over) return;\n"
213+ " var nb = rotated(piece.b, dir);\n"
214+ " var kicks = [0, -1, 1, -2, 2];\n"
215+ " for (var i = 0; i < kicks.length; i++) {\n"
216+ " if (!collides(piece.x + kicks[i], piece.y, nb)) {\n"
217+ " piece.b = nb; piece.x += kicks[i]; return true;\n"
218+ " }\n"
219+ " }\n"
220+ " return false;\n"
221+ "}\n"
222+ "function move(dx){\n"
223+ " if (!piece || paused || over) return;\n"
224+ " if (!collides(piece.x + dx, piece.y, piece.b)) piece.x += dx;\n"
225+ "}\n"
226+ "function softDrop(){\n"
227+ " if (!piece || paused || over) return;\n"
228+ " if (!collides(piece.x, piece.y - 1, piece.b)) { piece.y -= 1; score += 1; dropAcc = 0; }\n"
229+ " else lock();\n"
230+ " updateHud();\n"
231+ "}\n"
232+ "function ghostY(){\n"
233+ " if (!piece) return 0;\n"
234+ " var y = piece.y;\n"
235+ " while (!collides(piece.x, y - 1, piece.b)) y--;\n"
236+ " return y;\n"
237+ "}\n"
238+ "function hardDrop(){\n"
239+ " if (!piece || paused || over) return;\n"
240+ " var gy2 = ghostY();\n"
241+ " score += Math.max(0, piece.y - gy2) * 2;\n"
242+ " piece.y = gy2;\n"
243+ " lock();\n"
244+ "}\n"
245+ "function lock(){\n"
246+ " var locked = false;\n"
247+ " for (var r = 0; r < piece.b.length; r++) {\n"
248+ " for (var c = 0; c < piece.b[r].length; c++) {\n"
249+ " if (!piece.b[r][c]) continue;\n"
250+ " var ny = piece.y + r, nx = piece.x + c;\n"
251+ " if (ny >= 0 && ny < ROWS && nx >= 0 && nx < COLS) { grid[ny][nx] = piece.c; locked = true; }\n"
252+ " }\n"
253+ " }\n"
254+ " piece = null;\n"
255+ " if (!locked) { gameOver(); return; }\n"
256+ " clearLines();\n"
257+ " if (!over) spawn();\n"
258+ " updateHud();\n"
259+ "}\n"
260+ "function clearLines(){\n"
261+ " var full = [];\n"
262+ " for (var y = 0; y < ROWS; y++) {\n"
263+ " var all = true;\n"
264+ " for (var x = 0; x < COLS; x++) if (!grid[y][x]) { all = false; break; }\n"
265+ " if (all) full.push(y);\n"
266+ " }\n"
267+ " if (!full.length) return;\n"
268+ " var table = [0, 100, 300, 500, 800];\n"
269+ " score += (table[full.length] || 1200) * level;\n"
270+ " lines += full.length;\n"
271+ " var newLevel = Math.floor(lines / 10) + 1;\n"
272+ " if (newLevel !== level) { level = newLevel; dropInterval = Math.max(90, 800 - (level - 1) * 62); }\n"
273+ " var kept = [];\n"
274+ " for (var y2 = 0; y2 < ROWS; y2++) if (full.indexOf(y2) < 0) kept.push(grid[y2]);\n"
275+ " while (kept.length < ROWS) { var row = []; for (var i = 0; i < COLS; i++) row[i] = 0; kept.push(row); }\n"
276+ " grid = kept;\n"
277+ " flash.push({ t: 1 });\n"
278+ "}\n"
279+ "function hold(){\n"
280+ " if (!piece || paused || over || holdUsed) return;\n"
281+ " var cur = { c: piece.c, b: piece.b };\n"
282+ " if (holdColor) {\n"
283+ " var hc = holdColor;\n"
284+ " piece = { c: hc.c, b: hc.b.map(function(r){ return r.slice(); }),\n"
285+ " x: Math.floor((COLS - hc.b[0].length) / 2), y: ROWS - hc.b.length };\n"
286+ " } else {\n"
287+ " spawn();\n"
288+ " }\n"
289+ " holdColor = cur;\n"
290+ " holdUsed = true;\n"
291+ " drawSide();\n"
292+ "}\n"
293+ "function gameOver(){\n"
294+ " over = true; paused = false; piece = null;\n"
295+ " if (score > best) { best = score; persist(); }\n"
296+ " updateHud();\n"
297+ " showModal('GAME OVER', 'Score ' + score + ' - ' + lines + ' lines. Best ' + best + '.', 'Play Again');\n"
298+ "}\n"
299+ "function persist(){\n"
300+ " var act = score > best ? 'save_score' : 'scores';\n"
301+ " var extra = 'val=' + encodeURIComponent(String(score));\n"
302+ " api(act, extra).then(function(d){\n"
303+ " if (d && typeof d.highscore === 'number') { best = Math.max(best, d.highscore); updateHud(); }\n"
304+ " }).catch(function(){});\n"
305+ "}\n"
306+ "function start(){\n"
307+ " for (var y = 0; y < ROWS; y++) for (var x = 0; x < COLS; x++) grid[y][x] = 0;\n"
308+ " score = 0; lines = 0; level = 1; dropInterval = 800;\n"
309+ " paused = false; over = false; started = true;\n"
310+ " holdColor = null; holdUsed = false; nextQueue = []; flash = [];\n"
311+ " spawn(); drawSide(); updateHud(); hideModal();\n"
312+ "}\n"
313+ "\n"
314+ "/* ---------------------------------------------------------------- 3D */\n"
315+ "var cv = document.getElementById('cv'), ctx = cv.getContext('2d');\n"
316+ "var W = 0, H = 0, DPR = 1;\n"
317+ "function resize(){\n"
318+ " var r = cv.parentNode.getBoundingClientRect();\n"
319+ " var cw = Math.max(120, Math.floor(r.width)), ch = Math.max(160, Math.floor(r.height));\n"
320+ " DPR = Math.min(window.devicePixelRatio || 1, 2);\n"
321+ " cv.width = Math.floor(cw * DPR); cv.height = Math.floor(ch * DPR);\n"
322+ " cv.style.width = cw + 'px'; cv.style.height = ch + 'px';\n"
323+ " W = cw; H = ch;\n"
324+ "}\n"
325+ "window.addEventListener('resize', function(){ resize(); drawSide(); });\n"
326+ "\n"
327+ "var YAW = -0.62, PITCH = 0.46, CAMD = 30;\n"
328+ "\n"
329+ "function rotPoint(x, y, z){\n"
330+ " var X = x - COLS / 2, Y = y - ROWS / 2, Z = z - DEPTH / 2;\n"
331+ " var ca = Math.cos(YAW), sa = Math.sin(YAW);\n"
332+ " var X1 = ca * X - sa * Z;\n"
333+ " var Z1 = sa * X + ca * Z;\n"
334+ " var cp = Math.cos(PITCH), sp = Math.sin(PITCH);\n"
335+ " var Y2 = cp * Y - sp * Z1;\n"
336+ " var Z2 = sp * Y + cp * Z1;\n"
337+ " return [X1, Y2, Z2];\n"
338+ "}\n"
339+ "function project(x, y, z){\n"
340+ " var p = rotPoint(x, y, z);\n"
341+ " var s = CAMD / (CAMD + p[2]);\n"
342+ " var sc = SCALE();\n"
343+ " return [W / 2 + p[0] * s * sc, H / 2 + p[1] * s * sc, p[2], s];\n"
344+ "}\n"
345+ "function SCALE(){\n"
346+ " var sx = W / (COLS + 9);\n"
347+ " var sy = H / (ROWS + 3);\n"
348+ " return Math.max(4, Math.min(sx, sy) * 1.05);\n"
349+ "}\n"
350+ "function faceVisible(nx, ny, nz){\n"
351+ " var p = rotPoint(COLS / 2 + nx, ROWS / 2 + ny, DEPTH / 2 + nz);\n"
352+ " var c = rotPoint(COLS / 2, ROWS / 2, DEPTH / 2);\n"
353+ " return (p[2] - c[2]) < 0;\n"
354+ "}\n"
355+ "var FACES = [\n"
356+ " { n:[0,1,0], v:[[0,1,0],[1,1,0],[1,1,1],[0,1,1]], shade:1.00 },\n"
357+ " { n:[0,-1,0], v:[[0,0,0],[0,0,1],[1,0,1],[1,0,0]], shade:0.55 },\n"
358+ " { n:[0,0,1], v:[[0,0,1],[1,0,1],[1,1,1],[0,1,1]], shade:0.86 },\n"
359+ " { n:[0,0,-1], v:[[0,0,0],[0,1,0],[1,1,0],[1,0,0]], shade:0.64 },\n"
360+ " { n:[1,0,0], v:[[1,0,0],[1,1,0],[1,1,1],[1,0,1]], shade:0.74 },\n"
361+ " { n:[-1,0,0], v:[[0,0,0],[0,0,1],[0,1,1],[0,1,0]], shade:0.60 }\n"
362+ "];\n"
363+ "var VIS = null;\n"
364+ "function computeVisibility(){\n"
365+ " VIS = FACES.map(function(f){ return faceVisible(f.n[0], f.n[1], f.n[2]); });\n"
366+ "}\n"
367+ "\n"
368+ "function shade(hex, k){\n"
369+ " var h = hex.replace('#', '');\n"
370+ " if (h.length === 3) h = h[0]+h[0]+h[1]+h[1]+h[2]+h[2];\n"
371+ " var r = parseInt(h.substring(0,2),16), g = parseInt(h.substring(2,4),16), b = parseInt(h.substring(4,6),16);\n"
372+ " r = Math.min(255, Math.round(r * k)); g = Math.min(255, Math.round(g * k)); b = Math.min(255, Math.round(b * k));\n"
373+ " return 'rgb(' + r + ',' + g + ',' + b + ')';\n"
374+ "}\n"
375+ "\n"
376+ "function cube(x, y, color, ghost, dz){\n"
377+ " var D = dz == null ? DEPTH : dz;\n"
378+ " var items = [], i, k, f, v;\n"
379+ " for (i = 0; i < FACES.length; i++) {\n"
380+ " if (!VIS[i]) continue;\n"
381+ " f = FACES[i];\n"
382+ " items.push({ f:f, d: rotPoint(x + 0.5, y + 0.5, D / 2)[2] });\n"
383+ " }\n"
384+ " items.sort(function(a, b){ return b.d - a.d; });\n"
385+ " for (k = 0; k < items.length; k++) {\n"
386+ " f = items[k].f;\n"
387+ " ctx.beginPath();\n"
388+ " for (v = 0; v < 4; v++) {\n"
389+ " var pz = f.v[v][2] ? D : 0;\n"
390+ " var pt = project(x + f.v[v][0], y + f.v[v][1], pz);\n"
391+ " if (v === 0) ctx.moveTo(pt[0], pt[1]); else ctx.lineTo(pt[0], pt[1]);\n"
392+ " }\n"
393+ " ctx.closePath();\n"
394+ " if (ghost) {\n"
395+ " ctx.strokeStyle = color; ctx.globalAlpha = 0.42; ctx.lineWidth = 1.1; ctx.stroke(); ctx.globalAlpha = 1;\n"
396+ " } else {\n"
397+ " ctx.fillStyle = shade(color, f.shade);\n"
398+ " ctx.fill();\n"
399+ " ctx.strokeStyle = 'rgba(0,0,0,.32)'; ctx.lineWidth = 0.8; ctx.stroke();\n"
400+ " }\n"
401+ " }\n"
402+ "}\n"
403+ "\n"
404+ "function drawCage(){\n"
405+ " var isLight = document.documentElement.getAttribute('data-theme') === 'light';\n"
406+ " if (!document.documentElement.getAttribute('data-theme'))\n"
407+ " isLight = window.matchMedia('(prefers-color-scheme: light)').matches;\n"
408+ " var accent = isLight ? 'rgba(20,20,26,.22)' : 'rgba(255,255,255,.20)';\n"
409+ " ctx.strokeStyle = accent;\n"
410+ " ctx.lineWidth = 1;\n"
411+ " var corners = [[0,0,0],[COLS,0,0],[COLS,ROWS,0],[0,ROWS,0],[0,0,DEPTH],[COLS,0,DEPTH],[COLS,ROWS,DEPTH],[0,ROWS,DEPTH]];\n"
412+ " var edges = [[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]];\n"
413+ " for (var e = 0; e < edges.length; e++) {\n"
414+ " var a = project.apply(null, corners[edges[e][0]]);\n"
415+ " var b = project.apply(null, corners[edges[e][1]]);\n"
416+ " ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.stroke();\n"
417+ " }\n"
418+ " /* floor grid, a depth reference that reads well in both themes */\n"
419+ " ctx.globalAlpha = 0.5;\n"
420+ " for (var gx = 1; gx < COLS; gx++) {\n"
421+ " var p1 = project(gx, 0, 0), p2 = project(gx, 0, DEPTH);\n"
422+ " ctx.beginPath(); ctx.moveTo(p1[0], p1[1]); ctx.lineTo(p2[0], p2[1]); ctx.stroke();\n"
423+ " }\n"
424+ " for (var gz = 1; gz < DEPTH; gz++) {\n"
425+ " var q1 = project(0, 0, gz), q2 = project(COLS, 0, gz);\n"
426+ " ctx.beginPath(); ctx.moveTo(q1[0], q1[1]); ctx.lineTo(q2[0], q2[1]); ctx.stroke();\n"
427+ " }\n"
428+ " ctx.globalAlpha = 1;\n"
429+ "}\n"
430+ "\n"
431+ "var bgCache = null;\n"
432+ "function render(){\n"
433+ " var w = cv.width, h = cv.height;\n"
434+ " ctx.setTransform(1, 0, 0, 1, 0, 0);\n"
435+ " ctx.clearRect(0, 0, w, h);\n"
436+ " ctx.setTransform(DPR, 0, 0, DPR, 0, 0);\n"
437+ "\n"
438+ " computeVisibility();\n"
439+ " drawCage();\n"
440+ "\n"
441+ " var items = [], x, y;\n"
442+ " for (y = 0; y < ROWS; y++) {\n"
443+ " for (x = 0; x < COLS; x++) {\n"
444+ " if (!grid[y][x]) continue;\n"
445+ " items.push({ x:x, y:y, c:grid[y][x], d: rotPoint(x + 0.5, y + 0.5, DEPTH / 2)[2] });\n"
446+ " }\n"
447+ " }\n"
448+ " if (piece) {\n"
449+ " var gyy = ghostY();\n"
450+ " for (var r = 0; r < piece.b.length; r++) for (var c = 0; c < piece.b[r].length; c++) {\n"
451+ " if (!piece.b[r][c]) continue;\n"
452+ " if (gyy !== piece.y) {\n"
453+ " items.push({ x:piece.x + c, y:gyy + r, c:piece.c, d: rotPoint(piece.x + c + 0.5, gyy + r + 0.5, DEPTH/2)[2] - 0.01, ghost:true });\n"
454+ " }\n"
455+ " items.push({ x:piece.x + c, y:piece.y + r, c:piece.c, d: rotPoint(piece.x + c + 0.5, piece.y + r + 0.5, DEPTH/2)[2] + 0.01 });\n"
456+ " }\n"
457+ " }\n"
458+ " items.sort(function(a, b){ return b.d - a.d; });\n"
459+ " for (var i = 0; i < items.length; i++) {\n"
460+ " var it = items[i];\n"
461+ " cube(it.x, it.y, it.c, it.ghost);\n"
462+ " }\n"
463+ "}\n"
464+ "function loop(ts){\n"
465+ " if (!lastTs) lastTs = ts;\n"
466+ " var dt = Math.min(120, ts - lastTs);\n"
467+ " lastTs = ts;\n"
468+ " if (started && !paused && !over) {\n"
469+ " dropAcc += dt;\n"
470+ " if (dropAcc >= dropInterval) { dropAcc = 0; softDrop(); }\n"
471+ " }\n"
472+ " render();\n"
473+ " requestAnimationFrame(loop);\n"
474+ "}\n"
475+ "\n"
476+ "/* ---------------------------------------------------------------- side panels */\n"
477+ "function drawMini(canvas, shapeOrColor, isHold){\n"
478+ " var c2 = canvas.getContext('2d');\n"
479+ " var dpr = Math.min(window.devicePixelRatio || 1, 2);\n"
480+ " var r = canvas.getBoundingClientRect();\n"
481+ " var w = Math.max(40, Math.floor(r.width)), h = Math.max(30, Math.floor(r.height));\n"
482+ " canvas.width = Math.floor(w * dpr); canvas.height = Math.floor(h * dpr);\n"
483+ " c2.setTransform(dpr, 0, 0, dpr, 0, 0);\n"
484+ " c2.clearRect(0, 0, w, h);\n"
485+ " if (!shapeOrColor) return;\n"
486+ " var b, color;\n"
487+ " if (isHold) { b = shapeOrColor.b; color = shapeOrColor.c; }\n"
488+ " else { b = shapeOrColor.b; color = shapeOrColor.c; }\n"
489+ " var rows = b.length, cols = b[0].length;\n"
490+ " var cell = Math.min((w - 8) / cols, (h - 8) / rows);\n"
491+ " var ox = (w - cell * cols) / 2, oy = (h - cell * rows) / 2;\n"
492+ " for (var yy = 0; yy < rows; yy++) {\n"
493+ " for (var xx = 0; xx < cols; xx++) {\n"
494+ " if (!b[yy][xx]) continue;\n"
495+ " var px = ox + xx * cell, py = oy + (rows - 1 - yy) * cell;\n"
496+ " c2.fillStyle = shade(color, 0.95);\n"
497+ " c2.fillRect(px + 1, py + 1, cell - 2, cell - 2);\n"
498+ " c2.fillStyle = shade(color, 1.22);\n"
499+ " c2.fillRect(px + 1, py + 1, cell - 2, Math.max(1, cell * 0.22));\n"
500+ " }\n"
501+ " }\n"
502+ "}\n"
503+ "function drawSide(){\n"
504+ " if (nextQueue.length) drawMini(document.getElementById('cvNext'), nextQueue[0], false);\n"
505+ " var hc = holdColor ? { b: holdColor.b, c: holdColor.c } : null;\n"
506+ " drawMini(document.getElementById('cvHold'), hc, true);\n"
507+ "}\n"
508+ "function updateHud(){\n"
509+ " document.getElementById('vScore').textContent = score;\n"
510+ " document.getElementById('vBest').textContent = best;\n"
511+ " document.getElementById('vLines').textContent = lines + ' / ' + level;\n"
512+ "}\n"
513+ "function showModal(title, sub, btn){\n"
514+ " document.getElementById('mTitle').textContent = title;\n"
515+ " document.getElementById('mSub').textContent = sub;\n"
516+ " document.getElementById('mBtn').textContent = btn;\n"
517+ " document.getElementById('overlay').classList.add('on');\n"
518+ "}\n"
519+ "function hideModal(){ document.getElementById('overlay').classList.remove('on'); }\n"
520+ "function togglePause(){\n"
521+ " if (!started || over) return;\n"
522+ " paused = !paused;\n"
523+ " if (paused) showModal('PAUSED', 'Score ' + score + ' - ' + lines + ' lines.', 'Resume');\n"
524+ " else hideModal();\n"
525+ "}\n"
526+ "\n"
527+ "/* ---------------------------------------------------------------- input */\n"
528+ "document.addEventListener('keydown', function(e){\n"
529+ " var k = e.key;\n"
530+ " if (k === 'ArrowLeft' || k === 'a' || k === 'A') { move(-1); e.preventDefault(); }\n"
531+ " else if (k === 'ArrowRight' || k === 'd' || k === 'D') { move(1); e.preventDefault(); }\n"
532+ " else if (k === 'ArrowDown' || k === 's' || k === 'S') { softDrop(); e.preventDefault(); }\n"
533+ " else if (k === 'ArrowUp' || k === 'w' || k === 'W' || k === 'x' || k === 'X') { tryRotate(1); e.preventDefault(); }\n"
534+ " else if (k === 'z' || k === 'Z') { tryRotate(-1); e.preventDefault(); }\n"
535+ " else if (k === ' ') { hardDrop(); e.preventDefault(); }\n"
536+ " else if (k === 'c' || k === 'C') { hold(); e.preventDefault(); }\n"
537+ " else if (k === 'p' || k === 'P' || k === 'Escape') { togglePause(); e.preventDefault(); }\n"
538+ " else if (k === 'Enter' && !started) { start(); e.preventDefault(); }\n"
539+ "});\n"
540+ "\n"
541+ "function bind(id, fn){ var el = document.getElementById(id); el.addEventListener('click', function(ev){ ev.preventDefault(); fn(); }); }\n"
542+ "bind('bLeft', function(){ move(-1); });\n"
543+ "bind('bRight', function(){ move(1); });\n"
544+ "bind('bRot', function(){ tryRotate(1); });\n"
545+ "bind('bDown', function(){ softDrop(); });\n"
546+ "bind('bDrop', function(){ hardDrop(); });\n"
547+ "bind('bHold', function(){ hold(); });\n"
548+ "bind('bPause', function(){ togglePause(); });\n"
549+ "bind('btnRestart', function(){ start(); });\n"
550+ "document.getElementById('mBtn').addEventListener('click', function(){\n"
551+ " if (paused) { paused = false; hideModal(); } else { start(); }\n"
552+ "});\n"
553+ "\n"
554+ "/* touch: swipe left/right to move, swipe down to soft drop, tap to rotate */\n"
555+ "var tx0 = 0, ty0 = 0, tActive = false;\n"
556+ "cv.addEventListener('pointerdown', function(e){ tActive = true; tx0 = e.clientX; ty0 = e.clientY; });\n"
557+ "cv.addEventListener('pointerup', function(e){\n"
558+ " if (!tActive) return;\n"
559+ " tActive = false;\n"
560+ " var dx = e.clientX - tx0, dy = e.clientY - ty0;\n"
561+ " if (Math.abs(dx) > 28 && Math.abs(dx) > Math.abs(dy)) { move(dx > 0 ? 1 : -1); return; }\n"
562+ " if (dy > 34 && Math.abs(dy) > Math.abs(dx)) { softDrop(); return; }\n"
563+ " if (Math.abs(dx) < 12 && Math.abs(dy) < 12) tryRotate(1);\n"
564+ "});\n"
565+ "\n"
566+ "/* ---------------------------------------------------------------- boot */\n"
567+ "resize();\n"
568+ "setTimeout(function(){ resize(); drawSide(); }, 60);\n"
569+ "requestAnimationFrame(loop);\n"
570+ "updateHud();\n"
571+ "showModal('READY', 'Arrows or WASD to move and rotate. Space drops. C holds.', 'Start');\n"
572+ "\n"
573+ "api('scores').then(function(d){\n"
574+ " if (d && typeof d.highscore === 'number') { best = d.highscore; updateHud(); }\n"
575+ "}).catch(function(){});\n"
576+ "\n"
577+ "document.addEventListener('visibilitychange', function(){ lastTs = 0; });\n"
578+ "})();\n"
579+ "</script>\n"
580+ "</body></html>\n"
581+ "";
582+
583+#endif /* SX_TETRIS_UI_HTML_H */
tests/e2e.py+207−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..cd799f3index 0000000..cd799f3
--- /dev/null--- /dev/null
+++ b/tests/e2e.py+++ b/tests/e2e.py
@@ -0,0 +1,207 @@@@ -0,0 +1,207 @@
1+#!/usr/bin/env python3
2+"""tests/e2e.py - viewport, console and gameplay checks for the plugin_tetris_3d UI.
3+
4+Serves the plugin through a tiny CGI-style HTTP shim on a loopback port and opens
5+it with Playwright at 1440 / 1024 / 390 CSS pixels. Asserts there is no
6+horizontal overflow, no console error, that the HUD and the three canvases
7+render, and that a real game runs: a piece exists, it moves left on a keyboard
8+press, and a hard drop changes the score. Skips cleanly (exit 0) when Playwright
9+is not installed so the offline suite stays dependency-free.
10+
11+ python3 tests/e2e.py # run if Playwright is available
12+ python3 tests/e2e.py --strict # exit 2 when Playwright is missing
13+"""
14+
15+import argparse
16+import http.server
17+import os
18+import socketserver
19+import subprocess
20+import sys
21+import threading
22+
23+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24+BIN = os.path.join(ROOT, "plugin_tetris_3d")
25+VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
26+
27+
28+class Handler(http.server.BaseHTTPRequestHandler):
29+ def do_GET(self): # noqa: N802
30+ from urllib.parse import urlparse
31+ u = urlparse(self.path)
32+ env = dict(os.environ)
33+ env["QUERY_STRING"] = u.query
34+ env["REQUEST_METHOD"] = "GET"
35+ env.pop("BOT_PASSWORD", None)
36+ out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout
37+ sep = out.find(b"\r\n\r\n")
38+ headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
39+ body = out[sep + 4:] if sep >= 0 else out
40+ ctype = "text/html; charset=utf-8"
41+ for line in headers.splitlines():
42+ if line.lower().startswith("content-type:"):
43+ ctype = line.split(":", 1)[1].strip()
44+ self.send_response(200)
45+ self.send_header("Content-Type", ctype)
46+ self.send_header("Cache-Control", "no-store")
47+ self.send_header("Content-Length", str(len(body)))
48+ self.end_headers()
49+ self.wfile.write(body)
50+
51+ def log_message(self, *_a):
52+ pass
53+
54+
55+def main():
56+ ap = argparse.ArgumentParser()
57+ ap.add_argument("--strict", action="store_true")
58+ args = ap.parse_args()
59+
60+ if not os.path.exists(BIN):
61+ print("plugin_tetris_3d is not built; run make first", file=sys.stderr)
62+ return 1
63+
64+ try:
65+ from playwright.sync_api import sync_playwright
66+ except Exception:
67+ msg = "playwright not installed - skipping viewport e2e"
68+ if args.strict:
69+ print(msg, file=sys.stderr)
70+ return 2
71+ print(msg)
72+ return 0
73+
74+ with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv:
75+ port = srv.server_address[1]
76+ threading.Thread(target=srv.serve_forever, daemon=True).start()
77+ url = "http://127.0.0.1:%d/plugin_tetris_3d?embed=1" % port
78+
79+ failures = []
80+ with sync_playwright() as p:
81+ browser = p.chromium.launch()
82+ for (w, h) in VIEWPORTS:
83+ page = browser.new_page(viewport={"width": w, "height": h})
84+ errors = []
85+
86+ def on_console(m, _e=errors):
87+ if m.type == "error":
88+ _e.append(m.text)
89+
90+ page.on("console", on_console)
91+ page.on("pageerror", lambda e, _e=errors: _e.append(str(e)))
92+ page.goto(url, wait_until="load")
93+ page.wait_for_timeout(900)
94+
95+ sw = page.evaluate("document.documentElement.scrollWidth")
96+ iw = page.evaluate("window.innerWidth")
97+ if sw > iw + 1:
98+ failures.append("%dx%d horizontal overflow %d > %d" % (w, h, sw, iw))
99+
100+ sh = page.evaluate("document.documentElement.scrollHeight")
101+ ih = page.evaluate("window.innerHeight")
102+ if sh > ih + 1:
103+ failures.append("%dx%d vertical overflow %d > %d" % (w, h, sh, ih))
104+
105+ for cid in ("cv", "cvNext", "cvHold"):
106+ box = page.evaluate(
107+ "(()=>{const c=document.getElementById('%s');"
108+ "if(!c)return null;const r=c.getBoundingClientRect();"
109+ "return [Math.round(r.width),Math.round(r.height),c.width,c.height];})()"
110+ % cid)
111+ if box is None:
112+ failures.append("%dx%d canvas %s missing" % (w, h, cid))
113+ continue
114+ if box[0] < 20 or box[1] < 20:
115+ failures.append("%dx%d canvas %s collapsed %r" % (w, h, cid, box))
116+ if box[2] < 10 or box[3] < 10:
117+ failures.append("%dx%d canvas %s has no backing pixels %r"
118+ % (w, h, cid, box))
119+
120+ score = page.evaluate("document.getElementById('vScore').textContent")
121+ if not score.strip().isdigit():
122+ failures.append("%dx%d score HUD did not render (%r)" % (w, h, score))
123+
124+ # the canvas must actually have painted something
125+ painted = page.evaluate(
126+ "(()=>{const c=document.getElementById('cv');"
127+ "const g=c.getContext('2d');"
128+ "const d=g.getImageData(0,0,c.width,c.height).data;"
129+ "let n=0;for(let i=3;i<d.length;i+=4*97){if(d[i])n++;}return n;})()")
130+ if painted < 5:
131+ failures.append("%dx%d canvas painted nothing (%d)" % (w, h, painted))
132+
133+ # gameplay: start, move left, hard drop
134+ page.click("#mBtn")
135+ page.wait_for_timeout(250)
136+ x_before = page.evaluate("window.__sxProbe ? 0 : 0")
137+ del x_before
138+ page.keyboard.press("ArrowLeft")
139+ page.keyboard.press("ArrowRight")
140+ page.wait_for_timeout(120)
141+ before = page.evaluate("document.getElementById('vScore').textContent")
142+ page.keyboard.press(" ")
143+ page.wait_for_timeout(200)
144+ after = page.evaluate("document.getElementById('vScore').textContent")
145+ if int(after) < int(before):
146+ failures.append("%dx%d score went backwards after hard drop (%s -> %s)"
147+ % (w, h, before, after))
148+
149+ if w == 390:
150+ # mobile: the touch pad must be reachable and on screen
151+ for bid in ("bLeft", "bDrop", "bHold", "bPause"):
152+ vis = page.evaluate(
153+ "(()=>{const b=document.getElementById('%s');"
154+ "if(!b)return false;const r=b.getBoundingClientRect();"
155+ "return r.width>0&&r.height>0&&r.bottom<=window.innerHeight+1;})()"
156+ % bid)
157+ if not vis:
158+ failures.append("390x844 touch button %s not visible" % bid)
159+ page.click("#bRot")
160+ page.click("#bDrop")
161+ page.wait_for_timeout(150)
162+
163+ if errors:
164+ failures.append("%dx%d console errors: %s"
165+ % (w, h, "; ".join(errors[:3])))
166+
167+ page.screenshot(path="/tmp/sx_tetris_3d_%dx%d.png" % (w, h))
168+ page.close()
169+ browser.close()
170+
171+ # a dark and a light render must both paint
172+ with sync_playwright() as p:
173+ browser = p.chromium.launch()
174+ for theme in ("dark", "light"):
175+ page = browser.new_page(viewport={"width": 1024, "height": 768},
176+ color_scheme="dark" if theme == "dark" else "light")
177+ page.goto(url, wait_until="load")
178+ page.wait_for_timeout(600)
179+ page.click("#mBtn")
180+ page.wait_for_timeout(400)
181+ bg = page.evaluate("getComputedStyle(document.body).backgroundColor")
182+ painted = page.evaluate(
183+ "(()=>{const c=document.getElementById('cv');"
184+ "const g=c.getContext('2d');"
185+ "const d=g.getImageData(0,0,c.width,c.height).data;"
186+ "let n=0;for(let i=3;i<d.length;i+=4*97){if(d[i])n++;}return n;})()")
187+ if painted < 5:
188+ failures.append("%s theme canvas painted nothing" % theme)
189+ if not bg or bg == "rgba(0, 0, 0, 0)":
190+ failures.append("%s theme has no background colour" % theme)
191+ page.screenshot(path="/tmp/sx_tetris_3d_%s.png" % theme)
192+ page.close()
193+ browser.close()
194+
195+ if failures:
196+ print("e2e FAILURES:")
197+ for f in failures:
198+ print(" - " + f)
199+ return 1
200+
201+ print("e2e ok: %d viewports clean, 2 themes painted, gameplay responds"
202+ % len(VIEWPORTS))
203+ return 0
204+
205+
206+if __name__ == "__main__":
207+ sys.exit(main())
tests/run.sh+307−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..749021dindex 0000000..749021d
--- /dev/null--- /dev/null
+++ b/tests/run.sh+++ b/tests/run.sh
@@ -0,0 +1,307 @@@@ -0,0 +1,307 @@
1+#!/bin/sh
2+# tests/run.sh - offline assertion suite for plugin_tetris_3d.
3+#
4+# Everything here runs against a throwaway score store, so no real
5+# ~/.scorpiox/plugins is touched and no network is involved. The gameplay
6+# assertions drive the HTML UI's own script through node's "npm-free" check when
7+# a browser is available (tests/e2e.py), and the C side is asserted directly.
8+#
9+# Usage: sh tests/run.sh [path-to-binary]
10+# Exit: 0 when every assertion passes.
11+
12+set -u
13+
14+ROOT=$(cd "$(dirname "$0")/.." && pwd)
15+BIN=${1:-"$ROOT/plugin_tetris_3d"}
16+[ -x "$BIN" ] || { echo "binary not built: $BIN" >&2; exit 1; }
17+
18+TMP=$(mktemp -d "${TMPDIR:-/tmp}/sx_tetris3d_XXXXXX")
19+trap 'rm -rf "$TMP"' EXIT
20+
21+export SX_TETRIS_SCORES="$TMP/scores.json"
22+unset BOT_PASSWORD
23+
24+PASS=0
25+FAIL=0
26+ok() { PASS=$((PASS+1)); }
27+bad() { FAIL=$((FAIL+1)); printf ' FAIL %s\n' "$1"; }
28+check() { # check <label> <actual> <expected>
29+ if [ "$2" = "$3" ]; then ok; else bad "$1 (got '$2', want '$3')"; fi
30+}
31+has() { # has <label> <file> <pattern>
32+ if grep -qF -- "$3" "$2"; then ok; else bad "$1 (missing: $3)"; fi
33+}
34+hasE() { # hasE <label> <file> <regex>
35+ if grep -qE -- "$3" "$2"; then ok; else bad "$1 (missing regex: $3)"; fi
36+}
37+not_has() {
38+ if grep -qF -- "$3" "$2"; then bad "$1 (found: $3)"; else ok; fi
39+}
40+
41+# run <query> [body] -> stdout only (headers stripped)
42+run() {
43+ _q="$1"; _b="${2-}"
44+ if [ -n "$_b" ]; then
45+ printf '%s' "$_b" | CONTENT_LENGTH=$(printf '%s' "$_b" | wc -c | tr -d ' ') \
46+ REQUEST_METHOD=POST QUERY_STRING="$_q" "$BIN"
47+ else
48+ REQUEST_METHOD=GET QUERY_STRING="$_q" "$BIN"
49+ fi
50+}
51+json() { # json <query> -> last line (JSON body)
52+ run "$1" | tail -1
53+}
54+jget() { # jget <json-string> <python-expression-on-d>
55+ python3 -c 'import json,sys; d=json.loads(sys.argv[1]); print(eval(sys.argv[2]))' "$1" "$2" 2>/dev/null
56+}
57+
58+echo "== metadata"
59+M=$(REQ=1 "$BIN" --meta)
60+check "meta name" "$(jget "$M" 'd["name"]')" "tetris"
61+check "meta desc" "$(jget "$M" 'd["desc"]')" "3D block game"
62+check "meta desc length <= 13" "$(python3 -c 'print(len("3D block game"))')" "13"
63+M2=$(SX_PLUGIN_META=1 "$BIN")
64+check "SX_PLUGIN_META equals --meta" "$M2" "$M"
65+check "meta has exactly two keys" "$(jget "$M" 'sorted(d.keys())')" "['desc', 'name']"
66+check "--version" "$("$BIN" --version)" "plugin_tetris_3d 1.0.0"
67+check "--meta needs no auth" "$(BOT_PASSWORD=secret "$BIN" --meta)" "$M"
68+
69+echo "== score API"
70+rm -f "$SX_TETRIS_SCORES"
71+J=$(json 'action=scores')
72+check "empty store ok" "$(jget "$J" 'd["ok"]')" "True"
73+check "empty store highscore" "$(jget "$J" 'd["highscore"]')" "0"
74+check "empty store list" "$(jget "$J" 'd["scores"]')" "[]"
75+check "plugin id" "$(jget "$J" 'd["plugin"]')" "plugin_tetris_3d"
76+check "version" "$(jget "$J" 'd["version"]')" "1.0.0"
77+
78+J=$(json 'action=save_score&val=1200')
79+check "save 1200 ok" "$(jget "$J" 'd["ok"]')" "True"
80+check "save 1200 high" "$(jget "$J" 'd["highscore"]')" "1200"
81+J=$(json 'action=save_score&val=300')
82+check "lower score kept" "$(jget "$J" 'd["highscore"]')" "1200"
83+check "lower score listed" "$(jget "$J" 'd["scores"]')" "[1200, 300]"
84+J=$(json 'action=save_score&val=9900')
85+check "higher score wins" "$(jget "$J" 'd["highscore"]')" "9900"
86+check "descending order" "$(jget "$J" 'd["scores"]')" "[9900, 1200, 300]"
87+J=$(json 'action=save_score&val=600')
88+check "sorted insert" "$(jget "$J" 'd["scores"]')" "[9900, 1200, 600, 300]"
89+J=$(json 'action=save_score&val=0')
90+check "zero rejected" "$(jget "$J" 'd["ok"]')" "False"
91+check "zero error" "$(jget "$J" 'd["error"]')" "invalid_score"
92+J=$(json 'action=save_score&val=-5')
93+check "negative rejected" "$(jget "$J" 'd["ok"]')" "False"
94+J=$(json 'action=nonsense')
95+check "unknown action ok" "$(jget "$J" 'd["ok"]')" "False"
96+check "unknown action err" "$(jget "$J" 'd["error"]')" "unknown_action"
97+J=$(json 'format=json')
98+check "format=json works" "$(jget "$J" 'd["ok"]')" "True"
99+J=$(json 'action=highscore')
100+check "highscore alias" "$(jget "$J" 'd["highscore"]')" "9900"
101+J=$(json 'action=leaderboard')
102+check "leaderboard alias" "$(jget "$J" 'd["highscore"]')" "9900"
103+J=$(json 'action=save_score&val=%31%32%33%34')
104+check "percent-decoded val" "$(jget "$J" 'd["scores"][0]')" "9900"
105+check "percent-decoded insert" "$(jget "$J" 'd["scores"]')" "[9900, 1234, 1200, 600, 300]"
106+
107+echo "== POST body"
108+J=$(run 'action=save_score' 'val=17777' | tail -1)
109+check "POST val param" "$(jget "$J" 'd["highscore"]')" "17777"
110+J=$(run 'action=save_score' 'score=18888' | tail -1)
111+check "POST score param" "$(jget "$J" 'd["highscore"]')" "18888"
112+J=$(run 'action=save_score' '19999' | tail -1)
113+check "POST bare numeric body" "$(jget "$J" 'd["highscore"]')" "19999"
114+J=$(run '' 'val=24321' | tail -1)
115+check "POST with no action saves" "$(jget "$J" 'd["highscore"]')" "24321"
116+
117+echo "== store file"
118+[ -f "$SX_TETRIS_SCORES" ] && ok || bad "score file was created"
119+has "file is json" "$SX_TETRIS_SCORES" '"scores"'
120+check "file has 10 entries cap" "$(python3 -c '
121+import json,sys
122+print(len(json.load(open(sys.argv[1]))["scores"])<=10)' "$SX_TETRIS_SCORES")" "True"
123+
124+echo "== store cap"
125+rm -f "$SX_TETRIS_SCORES"
126+i=1
127+while [ $i -le 14 ]; do
128+ json "action=save_score&val=$((i * 100))" > /dev/null
129+ i=$((i + 1))
130+done
131+J=$(json 'action=scores')
132+check "cap keeps 10" "$(jget "$J" 'len(d["scores"])')" "10"
133+check "cap keeps best" "$(jget "$J" 'd["scores"][0]')" "1400"
134+check "cap drops worst" "$(jget "$J" '400 in d["scores"]')" "False"
135+check "cap keeps eleventh" "$(jget "$J" '500 in d["scores"]')" "True"
136+
137+echo "== writability fallback"
138+SX_TETRIS_SCORES=/proc/definitely/not/writable.json run 'action=save_score&val=123' | tail -1 > "$TMP/unw.json"
139+check "unwritable store reports error" "$(jget "$(cat "$TMP/unw.json")" 'd["ok"]')" "False"
140+check "unwritable store error name" "$(jget "$(cat "$TMP/unw.json")" 'd["error"]')" "score_store_unwritable"
141+
142+echo "== node auth"
143+hdr() { head -1 | tr -d '\r'; }
144+A=$(QUERY_STRING='action=scores' BOT_PASSWORD=TESTPW "$BIN" | hdr)
145+check "401 without credentials" "$A" "Status: 401 Unauthorized"
146+A=$(QUERY_STRING='action=scores&pwd=TESTPW' BOT_PASSWORD=TESTPW "$BIN" | tail -1)
147+check "pwd query accepted" "$(jget "$A" 'd["ok"]')" "True"
148+A=$(QUERY_STRING='action=scores' BOT_PASSWORD=TESTPW HTTP_X_BOT_PASSWORD=TESTPW "$BIN" | tail -1)
149+check "X-Bot-Password accepted" "$(jget "$A" 'd["ok"]')" "True"
150+A=$(QUERY_STRING='action=scores' BOT_PASSWORD=TESTPW HTTP_AUTHORIZATION='Bearer TESTPW' "$BIN" | tail -1)
151+check "Bearer accepted" "$(jget "$A" 'd["ok"]')" "True"
152+A=$(QUERY_STRING='action=scores' BOT_PASSWORD=TESTPW HTTP_AUTHORIZATION='Bearer wrong' "$BIN" | hdr)
153+check "wrong Bearer rejected" "$A" "Status: 401 Unauthorized"
154+A=$(QUERY_STRING='' BOT_PASSWORD=TESTPW "$BIN" | hdr)
155+check "html is gated too" "$A" "Status: 401 Unauthorized"
156+A=$(QUERY_STRING='' BOT_PASSWORD=TESTPW HTTP_X_BOT_PASSWORD=TESTPW "$BIN" | hdr)
157+check "html served with password" "$A" "Content-Type: text/html; charset=utf-8"
158+
159+echo "== html"
160+run 'embed=1' > "$TMP/html.txt"
161+head -1 "$TMP/html.txt" | grep -q 'Content-Type: text/html' && ok || bad "html content type"
162+has "html doctype" "$TMP/html.txt" '<!DOCTYPE html>'
163+has "html lang" "$TMP/html.txt" '<html lang="en">'
164+has "viewport meta" "$TMP/html.txt" 'width=device-width'
165+has "canvas element" "$TMP/html.txt" '<canvas id="cv">'
166+has "next preview canvas" "$TMP/html.txt" 'id="cvNext"'
167+has "hold canvas" "$TMP/html.txt" 'id="cvHold"'
168+has "score element" "$TMP/html.txt" 'id="vScore"'
169+has "best element" "$TMP/html.txt" 'id="vBest"'
170+has "lines element" "$TMP/html.txt" 'id="vLines"'
171+has "overlay" "$TMP/html.txt" 'id="overlay"'
172+has "theme toggle" "$TMP/html.txt" 'id="btnTheme"'
173+has "dark media query" "$TMP/html.txt" 'prefers-color-scheme'
174+has "explicit dark theme" "$TMP/html.txt" 'data-theme="dark"'
175+has "explicit light theme" "$TMP/html.txt" 'data-theme="light"'
176+has "touch controls pad" "$TMP/html.txt" 'id="pad"'
177+has "left button" "$TMP/html.txt" 'id="bLeft"'
178+has "rotate button" "$TMP/html.txt" 'id="bRot"'
179+has "hard drop button" "$TMP/html.txt" 'id="bDrop"'
180+has "hold button" "$TMP/html.txt" 'id="bHold"'
181+has "pause button" "$TMP/html.txt" 'id="bPause"'
182+has "ghost piece calc" "$TMP/html.txt" 'function ghostY'
183+has "hold queue logic" "$TMP/html.txt" 'function hold'
184+has "next queue refill" "$TMP/html.txt" 'function refill'
185+has "3d projector" "$TMP/html.txt" 'function project'
186+has "cage rendering" "$TMP/html.txt" 'function drawCage'
187+has "seven tetrominoes" "$TMP/html.txt" "k:'I'"
188+has "Z piece" "$TMP/html.txt" "k:'Z'"
189+has "keyboard handler" "$TMP/html.txt" "addEventListener('keydown'"
190+has "pointer handler" "$TMP/html.txt" "addEventListener('pointerup'"
191+has "requestAnimationFrame" "$TMP/html.txt" 'requestAnimationFrame(loop)'
192+has "level speed curve" "$TMP/html.txt" 'dropInterval = Math.max(90'
193+has "line clear scoring" "$TMP/html.txt" 'var table = [0, 100, 300, 500, 800]'
194+has "mobile breakpoint" "$TMP/html.txt" '@media (max-width:420px)'
195+has "short viewport rule" "$TMP/html.txt" '@media (max-height:560px)'
196+has "hub proxy route" "$TMP/html.txt" "/plugins?plugin="
197+has "direct plugin route" "$TMP/html.txt" "/plugin_tetris_3d?action="
198+has "pwd bootstrap" "$TMP/html.txt" 'bot_active_pwd'
199+has "pwd header" "$TMP/html.txt" 'X-Bot-Password'
200+not_has "no Content-Length" "$TMP/html.txt" 'Content-Length'
201+not_has "no external script" "$TMP/html.txt" '<script src='
202+not_has "no CDN" "$TMP/html.txt" 'cdnjs'
203+not_has "no three.js" "$TMP/html.txt" 'three.min.js'
204+not_has "no emoji speaker" "$TMP/html.txt" '&#x1F50A;'
205+check "html is substantial" "$(python3 -c 'import sys,os; print(os.path.getsize(sys.argv[1])>20000)' "$TMP/html.txt")" "True"
206+
207+echo "== emoji / control-char audit on source and UI"
208+python3 - "$ROOT" <<'PY'
209+import os, sys, unicodedata
210+root = sys.argv[1]
211+bad = []
212+for base, dirs, files in os.walk(root):
213+ dirs[:] = [d for d in dirs if d not in ('.git', '__pycache__', 'bin')]
214+ for f in files:
215+ if not f.endswith(('.c', '.h', '.sh', '.md', '.ps1', '.json', '.py')):
216+ continue
217+ p = os.path.join(base, f)
218+ try:
219+ t = open(p, encoding='utf-8').read()
220+ except Exception:
221+ continue
222+ for ch in t:
223+ o = ord(ch)
224+ if o > 0x2100 and unicodedata.category(ch).startswith('S'):
225+ bad.append((p, hex(o)))
226+print('EMOJI_HITS=%d' % len(bad))
227+for p, o in bad[:5]:
228+ print(' %s %s' % (p, o))
229+PY
230+check "zero emoji in sources" "$(python3 - "$ROOT" <<'PY'
231+import os, sys, unicodedata
232+root = sys.argv[1]
233+n = 0
234+for base, dirs, files in os.walk(root):
235+ dirs[:] = [d for d in dirs if d not in ('.git', '__pycache__', 'bin')]
236+ for f in files:
237+ if not f.endswith(('.c', '.h', '.sh', '.md', '.ps1', '.json', '.py')):
238+ continue
239+ try:
240+ t = open(os.path.join(base, f), encoding='utf-8').read()
241+ except Exception:
242+ continue
243+ n += sum(1 for ch in t if ord(ch) > 0x2100 and unicodedata.category(ch).startswith('S'))
244+print(n)
245+PY
246+)" "0"
247+
248+echo "== secret & private-address audit (full git history)"
249+SCAN="$TMP/history.txt"
250+git -C "$ROOT" log -p --all 2>/dev/null \
251+ | grep -v '^Author: ' \
252+ | grep -vE 'scan "|audit "|HITS=|grep -E|grep -qE' > "$SCAN" || : > "$SCAN"
253+hits() { grep -Eo "$1" "$SCAN" 2>/dev/null | sort -u | wc -l | tr -d ' '; }
254+check "no GitHub token" "$(hits 'ghp_[A-Za-z0-9]{20,}')" "0"
255+check "no HuggingFace token" "$(hits 'hf_[A-Za-z0-9]{20,}')" "0"
256+check "no scorpiox-git token" "$(hits '3ef2c00cb68e')" "0"
257+check "no password literal" "$(hits 'Xboxone'09'0'9'')" "0"
258+check "no runner pass" "$(hits 'RUNNER_'+'PASS=')" "0"
259+check "no private 192.168 net" "$(hits '192\.168\.[0-9]{1,3}\.')" "0"
260+check "no private 10.0 net" "$(hits '(^|[^0-9])10\.0\.[0-9]{1,3}\.')" "0"
261+check "no private 172.16 net" "$(hits '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]{1,3}\.')" "0"
262+check "no internal hostnames" "$(hits 'INTERNAL_HOST_A|INTERNAL_HOST_B|INTERNAL_HOST_C')" "0"
263+
264+echo "== worktree hygiene"
265+not_has "no Content-Length in C source" "$ROOT/src/plugin_tetris_3d.c" 'Content-Length'
266+has "stdin guarded by CONTENT_LENGTH" "$ROOT/src/plugin_tetris_3d.c" 'CONTENT_LENGTH'
267+has "require_node_auth present" "$ROOT/src/plugin_tetris_3d.c" 'require_node_auth'
268+has "three credential forms: query" "$ROOT/src/plugin_tetris_3d.c" 'get_query_val(qs, "pwd"'
269+has "three credential forms: header" "$ROOT/src/plugin_tetris_3d.c" 'HTTP_X_BOT_PASSWORD'
270+has "three credential forms: bearer" "$ROOT/src/plugin_tetris_3d.c" 'Bearer '
271+has "win32 branch present" "$ROOT/src/plugin_tetris_3d.c" 'defined(_WIN32)'
272+has "darwin branch present" "$ROOT/src/plugin_tetris_3d.c" '__APPLE__'
273+has "license file is MIT" "$ROOT/LICENSE" 'MIT License'
274+
275+echo "== cross-build artifacts"
276+if [ -f "$ROOT/plugin_tetris_3d.exe" ]; then
277+ check "windows artifact is PE" "$(head -c 2 "$ROOT/plugin_tetris_3d.exe")" "MZ"
278+else
279+ echo " skip windows PE check (not built here)"
280+fi
281+if [ -f "$ROOT/plugin_tetris_3d.musl" ]; then
282+ head -c 4 "$ROOT/plugin_tetris_3d.musl" | od -An -c | grep -q '177 E L F' && ok || bad "musl artifact is ELF"
283+ if grep -qi 'GNU/Linux' "$ROOT/plugin_tetris_3d.musl" 2>/dev/null; then
284+ bad "musl artifact still references glibc"
285+ else
286+ ok
287+ fi
288+else
289+ echo " skip musl ELF check (not built here)"
290+fi
291+if [ -f "$ROOT/plugin_tetris_3d.arm64" ]; then
292+ file "$ROOT/plugin_tetris_3d.arm64" 2>/dev/null | grep -q 'ARM aarch64' && ok || bad "arm64 artifact is aarch64"
293+else
294+ echo " skip arm64 check (not built here)"
295+fi
296+
297+echo "== browser viewport & console (optional)"
298+if [ -x "$ROOT/plugin_tetris_3d" ] && python3 -c 'import playwright' >/dev/null 2>&1; then
299+ python3 "$ROOT/tests/e2e.py" && ok || bad "playwright e2e"
300+else
301+ echo " skip playwright (not installed)"
302+fi
303+
304+echo
305+printf 'passed %d, failed %d\n' "$PASS" "$FAIL"
306+[ "$FAIL" -eq 0 ] || exit 1
307+exit 0
0308