plainscript-lang 1.0.3 → 1.0.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +836 -188
- package/compiler/cli.js +68 -4
- package/compiler/dependency-detector.js +6 -2
- package/compiler/generator.js +737 -51
- package/compiler/lexer.js +12 -0
- package/compiler/parser.js +184 -14
- package/compiler/version.js +1 -1
- package/docs/CAPABILITY_GAP_AUDIT.md +32 -5
- package/docs/GAME-PROMPT.md +915 -0
- package/docs/PLAINSCRIPT-SPEC.md +264 -3
- package/docs/index.html +41 -33
- package/docs/logo-pln.jpg +0 -0
- package/docs/visualization-example.svg +32 -0
- package/docs/website/script.js +130 -1
- package/docs/website/style.css +253 -122
- package/examples/ai-providers.pln +1 -1
- package/examples/arrays.pln +1 -1
- package/examples/async-errors.pln +1 -1
- package/examples/auth-api.pln +1 -1
- package/examples/auth-sessions.pln +1 -1
- package/examples/basics.pln +1 -1
- package/examples/bots.pln +1 -1
- package/examples/browser-interactive/README.md +29 -0
- package/examples/browser-interactive/public/index.html +83 -0
- package/examples/browser-interactive/public/interactive.js +27 -0
- package/examples/browser-interactive/src/interactive.pln +34 -0
- package/examples/cache-and-jobs.pln +1 -1
- package/examples/cache-schedule.pln +1 -1
- package/examples/canvas-game/README.md +34 -0
- package/examples/canvas-game/public/game.js +131 -0
- package/examples/canvas-game/public/index.html +48 -0
- package/examples/canvas-game/src/game.pln +139 -0
- package/examples/collections.pln +1 -1
- package/examples/concurrency.pln +1 -1
- package/examples/conditions.pln +1 -1
- package/examples/database.pln +1 -1
- package/examples/day2.pln +1 -1
- package/examples/day3.pln +1 -1
- package/examples/deployment.pln +1 -1
- package/examples/email-send.pln +1 -1
- package/examples/error-handling.pln +1 -1
- package/examples/expressions.pln +1 -1
- package/examples/file-uploads.pln +1 -1
- package/examples/files-and-config.pln +1 -1
- package/examples/files.pln +1 -1
- package/examples/football-backend/app.pln +1 -1
- package/examples/functions.pln +1 -1
- package/examples/hello.pln +1 -1
- package/examples/http-client.pln +1 -1
- package/examples/http.pln +1 -1
- package/examples/id-verification/app.pln +1 -1
- package/examples/javascript-library/README.md +54 -0
- package/examples/javascript-library/package-lock.json +21 -0
- package/examples/javascript-library/package.json +8 -0
- package/examples/javascript-library/public/config.json +4 -0
- package/examples/javascript-library/public/index.html +40 -0
- package/examples/javascript-library/src/interop.pln +53 -0
- package/examples/json.pln +1 -1
- package/examples/loops.pln +1 -1
- package/examples/modules/app.pln +1 -1
- package/examples/modules/main.pln +1 -1
- package/examples/modules/math.pln +1 -1
- package/examples/mongo.pln +1 -1
- package/examples/objects.pln +1 -1
- package/examples/ocr.pln +1 -1
- package/examples/packages.pln +1 -1
- package/examples/record-kinds.pln +1 -1
- package/examples/records.pln +1 -1
- package/examples/rest-api-fetch.pln +1 -1
- package/examples/rest-api.pln +1 -1
- package/examples/scheduled-tasks.pln +1 -1
- package/examples/search-and-filter.pln +1 -1
- package/examples/server.pln +1 -1
- package/examples/sessions-and-cookies.pln +1 -1
- package/examples/sqlite.pln +1 -1
- package/examples/start.pln +1 -1
- package/examples/stdlib.pln +1 -1
- package/examples/string-verbs.pln +1 -1
- package/examples/telegram-ai-bot.pln +1 -1
- package/examples/telegram-bot.pln +1 -1
- package/examples/testing.pln +1 -1
- package/examples/three-dimensional/README.md +51 -0
- package/examples/three-dimensional/public/index.html +33 -0
- package/examples/three-dimensional/src/scene.pln +34 -0
- package/examples/visualization.pln +12 -0
- package/examples/web-api.pln +1 -1
- package/examples/web-app.pln +1 -1
- package/examples/websocket-server.pln +1 -1
- package/examples/websocket.pln +1 -1
- package/examples/whatsapp-bot/pairing.pln +24 -2
- package/examples/whatsapp-bot/qr.pln +18 -2
- package/package.json +5 -3
- package/docs/logo.jpg +0 -0
|
@@ -0,0 +1,915 @@
|
|
|
1
|
+
# PlainScript Game Development Prompt Guide (v1.0.36)
|
|
2
|
+
|
|
3
|
+
The standing instruction sheet for AI agents asked to build games and
|
|
4
|
+
interactive browser apps in PlainScript.
|
|
5
|
+
|
|
6
|
+
## Standing instructions for AI agents
|
|
7
|
+
|
|
8
|
+
You are an AI agent building a game or interactive browser app. PlainScript is
|
|
9
|
+
the source of truth. This guide and `docs/PLAINSCRIPT-SPEC.md` describe what
|
|
10
|
+
the compiler actually implements.
|
|
11
|
+
|
|
12
|
+
- **Work in PlainScript.** Write `.pln`, compile it, ship the generated JS. Do
|
|
13
|
+
not hand-rewrite the logic in JavaScript.
|
|
14
|
+
- **Rule Zero — trust the compiler, nothing else.** Before you claim anything
|
|
15
|
+
works, run `node compiler/cli.js check <file.pln>` (or `plainscript check`).
|
|
16
|
+
If it does not compile, it does not work.
|
|
17
|
+
- **You may import and CALL any JavaScript library** — canvas, Web Audio,
|
|
18
|
+
three.js, matter.js, npm packages, browser globals. `new Type(args)`, member
|
|
19
|
+
chains, property assignment, promises, and callbacks all work.
|
|
20
|
+
- **Never rewrite PlainScript project logic in JavaScript** just because the
|
|
21
|
+
underlying API is JS. A library is *called* from PlainScript; game logic
|
|
22
|
+
stays in `.pln`. JS is the guest library, not the host language.
|
|
23
|
+
|
|
24
|
+
Every PlainScript block you show a user must compile — check it first.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## 1. Philosophy: intent-first, never rewrite in JavaScript (cardinal rule)
|
|
29
|
+
|
|
30
|
+
PlainScript is intent-oriented: you describe *what* the game should do and the
|
|
31
|
+
compiler generates JavaScript. One hard rule — **game logic lives in
|
|
32
|
+
PlainScript**. v1.0.36 reaches into any JS API from `.pln`, which makes
|
|
33
|
+
dropping to JS tempting; do not. Every browser capability below stays
|
|
34
|
+
reachable without leaving PlainScript.
|
|
35
|
+
|
|
36
|
+
- Loop, state, and collision logic are PlainScript.
|
|
37
|
+
- Graphics, math, and platform features are JS *libraries* you call.
|
|
38
|
+
- No built-in? `use` / `bring` a library and call it. Never transplant the
|
|
39
|
+
project's logic into the library's language.
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## 2. Project structure
|
|
44
|
+
|
|
45
|
+
```text
|
|
46
|
+
my-game/
|
|
47
|
+
src/
|
|
48
|
+
game.pln client-side game logic (compiled to the browser)
|
|
49
|
+
server.pln optional: web app that serves public/
|
|
50
|
+
helpers.pln optional: shared .pln modules, imported via `bring`
|
|
51
|
+
public/
|
|
52
|
+
index.html shell page: <canvas>, HUD divs, <script src="game.js">
|
|
53
|
+
game.js compiled browser bundle (build output)
|
|
54
|
+
package.json optional; only needed for npm libraries
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`src/game.pln` holds all client logic; `src/server.pln` (optional) is a Node
|
|
58
|
+
web app that serves the page; `public/index.html` is a dumb shell owning the
|
|
59
|
+
canvas and script tag; `public/game.js` is build output, never hand-edited;
|
|
60
|
+
`src/*.pln` helpers are pulled in with `bring name from "./helpers.pln"`.
|
|
61
|
+
Keep server and client logic in separate files — different runtimes.
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## 3. Browser target / how a game is served
|
|
66
|
+
|
|
67
|
+
A game is static files. `server.pln` — `serve folder "public"` exposes every
|
|
68
|
+
file under `public/` at `/`, and `reply file` sends the HTML shell for the
|
|
69
|
+
root path:
|
|
70
|
+
|
|
71
|
+
```plainscript
|
|
72
|
+
web app
|
|
73
|
+
serve folder "public"
|
|
74
|
+
|
|
75
|
+
route get "/"
|
|
76
|
+
reply file "public/index.html"
|
|
77
|
+
done
|
|
78
|
+
|
|
79
|
+
start 3000
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Build the client into the served folder:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
node compiler/cli.js build src/game.pln -o public/game.js
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`index.html` loads the compiled bundle with a plain script tag:
|
|
89
|
+
|
|
90
|
+
```html
|
|
91
|
+
<canvas id="game" width="640" height="480"></canvas>
|
|
92
|
+
<button id="restart" type="button">Restart</button>
|
|
93
|
+
<script src="game.js"></script>
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
**Package-free JS is browser-`<script>`-safe.** Without an npm import the
|
|
97
|
+
generated code has no `require()` — it is an async IIFE with a guarded
|
|
98
|
+
`module.exports` tail, so it loads as a plain script.
|
|
99
|
+
|
|
100
|
+
**When you need an npm library in the browser:**
|
|
101
|
+
|
|
102
|
+
1. **CDN global (preferred, stays package-free).** Load the library in
|
|
103
|
+
`index.html` *before* `game.js`; it becomes a browser global that
|
|
104
|
+
PlainScript calls directly — no `use`, no bundler:
|
|
105
|
+
|
|
106
|
+
```html
|
|
107
|
+
<script src="https://unpkg.com/three@0.160.0/build/three.min.js"></script>
|
|
108
|
+
<script src="game.js"></script>
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
2. **Bundler.** For `bring name from "pkg"`, compile to `public/game.js`, then
|
|
112
|
+
run it through a bundler (esbuild, Vite, Rollup) that inlines
|
|
113
|
+
`node_modules`.
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## 4. Rendering options
|
|
118
|
+
|
|
119
|
+
### 4.1 Canvas 2D
|
|
120
|
+
|
|
121
|
+
Default for 2D games — get the element, its 2D context, draw each frame:
|
|
122
|
+
|
|
123
|
+
```plainscript
|
|
124
|
+
remember canvas as document.getElementById("game")
|
|
125
|
+
remember ctx as canvas.getContext("2d")
|
|
126
|
+
canvas.width becomes 640
|
|
127
|
+
canvas.height becomes 480
|
|
128
|
+
|
|
129
|
+
make step(t)
|
|
130
|
+
ctx.clearRect(0, 0, 640, 480)
|
|
131
|
+
ctx.fillStyle becomes "#40c463"
|
|
132
|
+
ctx.fillRect(40, 40, 120, 60)
|
|
133
|
+
requestAnimationFrame(step)
|
|
134
|
+
done
|
|
135
|
+
|
|
136
|
+
requestAnimationFrame(step)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Canvas state is property interop — `fillStyle becomes ...`, `strokeStyle
|
|
140
|
+
becomes ...`, `font becomes ...` — then a draw call. Colors like `"#0d1117"`
|
|
141
|
+
are just strings. Match the canvas backing size to its display size so nothing
|
|
142
|
+
drifts on resize:
|
|
143
|
+
|
|
144
|
+
```plainscript
|
|
145
|
+
remember winW as window.innerWidth
|
|
146
|
+
remember winH as window.innerHeight
|
|
147
|
+
canvas.width becomes winW
|
|
148
|
+
canvas.height becomes winH
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Clear the whole canvas each frame (`clearRect`) or repaint the background;
|
|
152
|
+
skip both and the old frame bleeds through.
|
|
153
|
+
|
|
154
|
+
### 4.2 WebGL
|
|
155
|
+
|
|
156
|
+
`webglContext(canvas)` gets the context, `glShader` compiles a shader (throws a
|
|
157
|
+
teaching error on failure), `glProgram` links vertex + fragment shaders,
|
|
158
|
+
`glBuffer` uploads an `ARRAY_BUFFER` (`STATIC_DRAW`); all WebGL calls are
|
|
159
|
+
ordinary methods. One-time setup:
|
|
160
|
+
|
|
161
|
+
```plainscript
|
|
162
|
+
remember canvas as document.getElementById("gl")
|
|
163
|
+
remember gl as webglContext(canvas)
|
|
164
|
+
gl.viewport(0, 0, 640, 480)
|
|
165
|
+
gl.clearColor(0.1, 0.12, 0.15, 1)
|
|
166
|
+
|
|
167
|
+
remember vs as glShader(gl, "VERTEX_SHADER", `
|
|
168
|
+
attribute vec2 a;
|
|
169
|
+
void main() {
|
|
170
|
+
gl_Position = vec4(a, 0.0, 1.0);
|
|
171
|
+
}
|
|
172
|
+
`)
|
|
173
|
+
remember fs as glShader(gl, "FRAGMENT_SHADER", `
|
|
174
|
+
precision mediump float;
|
|
175
|
+
void main() {
|
|
176
|
+
gl_FragColor = vec4(0.25, 0.76, 0.38, 1.0);
|
|
177
|
+
}
|
|
178
|
+
`)
|
|
179
|
+
remember prog as glProgram(gl, vs, fs)
|
|
180
|
+
remember buf as glBuffer(gl, [0.0, 0.0, 1.0, 0.0, 0.0, 1.0])
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Per-frame render — keep setup out of the loop:
|
|
184
|
+
|
|
185
|
+
```plainscript
|
|
186
|
+
make renderTriangle()
|
|
187
|
+
gl.clear(gl.COLOR_BUFFER_BIT)
|
|
188
|
+
gl.useProgram(prog)
|
|
189
|
+
gl.drawArrays(gl.TRIANGLES, 0, 3)
|
|
190
|
+
done
|
|
191
|
+
|
|
192
|
+
every frame
|
|
193
|
+
renderTriangle()
|
|
194
|
+
done
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### 4.3 WebGPU
|
|
198
|
+
|
|
199
|
+
No special syntax — plain member-chain interop like WebGL, guarded, with the
|
|
200
|
+
promise verbs for async parts. Do not over-promise; support depends on the
|
|
201
|
+
browser/GPU:
|
|
202
|
+
|
|
203
|
+
```plainscript
|
|
204
|
+
make initGpu()
|
|
205
|
+
if navigator.gpu is not undefined
|
|
206
|
+
remember adapter as wait for navigator.gpu.requestAdapter()
|
|
207
|
+
remember device as wait for adapter.requestDevice()
|
|
208
|
+
show device
|
|
209
|
+
done
|
|
210
|
+
done
|
|
211
|
+
initGpu()
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### 4.4 Rendering libraries (three.js, Babylon.js, ...)
|
|
215
|
+
|
|
216
|
+
Load via CDN global (section 3) or npm import; construct with `new Type(args)`;
|
|
217
|
+
drive with PlainScript:
|
|
218
|
+
|
|
219
|
+
```plainscript
|
|
220
|
+
remember scene as new THREE.Scene()
|
|
221
|
+
remember camera as new THREE.PerspectiveCamera(75, 640 / 480, 0.1, 1000)
|
|
222
|
+
remember renderer as new THREE.WebGLRenderer({antialias: true})
|
|
223
|
+
renderer.setSize(640, 480)
|
|
224
|
+
document.getElementById("stage").appendChild(renderer.domElement)
|
|
225
|
+
|
|
226
|
+
remember geometry as new THREE.BoxGeometry(1, 1, 1)
|
|
227
|
+
remember material as new THREE.MeshStandardMaterial({color: 0x40c463})
|
|
228
|
+
remember mesh as new THREE.Mesh(geometry, material)
|
|
229
|
+
scene.add(mesh)
|
|
230
|
+
camera.position.set(0, 0, 5)
|
|
231
|
+
make loop()
|
|
232
|
+
mesh.rotation.x becomes mesh.rotation.x + 0.01
|
|
233
|
+
mesh.rotation.y becomes mesh.rotation.y + 0.01
|
|
234
|
+
renderer.render(scene, camera)
|
|
235
|
+
requestAnimationFrame(loop)
|
|
236
|
+
done
|
|
237
|
+
requestAnimationFrame(loop)
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
v1.0.36 adds hex literals (`0xRRGGBB`): numeric colors use `0xffffff` instead
|
|
241
|
+
of magic decimals, and a `"#ffffff"` string works too — THREE accepts all
|
|
242
|
+
three.
|
|
243
|
+
|
|
244
|
+
---
|
|
245
|
+
|
|
246
|
+
## 5. Input handling
|
|
247
|
+
|
|
248
|
+
The canonical idiom: **event handlers only record intent; the loop applies
|
|
249
|
+
it.** Keep a `keys{}` map, set flags in `keydown`/`keyup`, read the map inside
|
|
250
|
+
the loop. This avoids OS key-repeat and keeps one writer (the loop) for state.
|
|
251
|
+
|
|
252
|
+
```plainscript
|
|
253
|
+
remember keys as {}
|
|
254
|
+
when document "keydown" happens as ke
|
|
255
|
+
keys[ke.key] becomes true
|
|
256
|
+
done
|
|
257
|
+
when document "keyup" happens as ke
|
|
258
|
+
keys[ke.key] becomes false
|
|
259
|
+
done
|
|
260
|
+
|
|
261
|
+
remember player as {x: 320}
|
|
262
|
+
make step(dt)
|
|
263
|
+
if keys["ArrowLeft"] is true
|
|
264
|
+
player.x becomes player.x - 240 * dt
|
|
265
|
+
done
|
|
266
|
+
done
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
- Never mutate world state inside an event handler — set a flag, let the loop
|
|
270
|
+
consume it.
|
|
271
|
+
- `when <target> "<event>" happens` → `target.addEventListener(event, ...)`
|
|
272
|
+
with the parameter named via `as name` (default `event`).
|
|
273
|
+
- Named keys (`"ArrowLeft"`) or characters (`keys["a"]`) come from `ke.key`.
|
|
274
|
+
|
|
275
|
+
`localPoint(event, canvas)` maps client coordinates to canvas pixels:
|
|
276
|
+
|
|
277
|
+
```plainscript
|
|
278
|
+
remember canvas as select("canvas")
|
|
279
|
+
remember aim as {x: 0, y: 0}
|
|
280
|
+
|
|
281
|
+
when canvas "pointermove" happens as e
|
|
282
|
+
remember p as localPoint(e, canvas)
|
|
283
|
+
aim.x becomes p.x
|
|
284
|
+
aim.y becomes p.y
|
|
285
|
+
done
|
|
286
|
+
|
|
287
|
+
when canvas "touchmove" happens as e
|
|
288
|
+
e.preventDefault()
|
|
289
|
+
done
|
|
290
|
+
|
|
291
|
+
when window "wheel" happens as e
|
|
292
|
+
show e.deltaY
|
|
293
|
+
done
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
Touch reuses pointer events (`"touchmove"`) — call `e.preventDefault()` when
|
|
297
|
+
you own the gesture; `"wheel"` gives `e.deltaY` for zoom; `gamepads()` returns
|
|
298
|
+
connected pads to read inside the loop; drag-and-drop files arrive via
|
|
299
|
+
`droppedFiles(event)` in a `drop` handler.
|
|
300
|
+
|
|
301
|
+
---
|
|
302
|
+
|
|
303
|
+
## 6. Animation loop and delta time
|
|
304
|
+
|
|
305
|
+
The browser runs a single-threaded event loop; the only good loop is
|
|
306
|
+
`requestAnimationFrame` (rAF). A `while true` or long synchronous loop blocks
|
|
307
|
+
rendering, input, and audio — the page freezes. Never write one.
|
|
308
|
+
|
|
309
|
+
rAF passes a millisecond timestamp — difference, normalize to seconds, and
|
|
310
|
+
movement is frame-rate independent:
|
|
311
|
+
|
|
312
|
+
```plainscript
|
|
313
|
+
remember lastTick as 0
|
|
314
|
+
make loop(t)
|
|
315
|
+
remember dt as (t - lastTick) / 1000
|
|
316
|
+
if dt is above 0
|
|
317
|
+
step(dt)
|
|
318
|
+
done
|
|
319
|
+
lastTick becomes t
|
|
320
|
+
requestAnimationFrame(loop)
|
|
321
|
+
done
|
|
322
|
+
requestAnimationFrame(loop)
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
Cap `dt` (skip the step after a long stall) so a background-tab resume does not
|
|
326
|
+
jump the sim forward by seconds. For loops that do not need delta time, the
|
|
327
|
+
short form is `every frame ... done` (still rAF under the hood — see the
|
|
328
|
+
Appendix); use rAF + `dt` when movement must be time-based.
|
|
329
|
+
|
|
330
|
+
---
|
|
331
|
+
|
|
332
|
+
## 7. Asset loading
|
|
333
|
+
|
|
334
|
+
Built-in loaders return promises and **auto-await** — no `await` written:
|
|
335
|
+
|
|
336
|
+
```plainscript
|
|
337
|
+
remember bg as loadImage("img/background.png")
|
|
338
|
+
remember sfx as loadAudio("mp3/click.mp3")
|
|
339
|
+
remember manifest as fetchJson("assets/manifest.json")
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
- `loadImage(url)` → an `Image` ready for `ctx.drawImage(img, x, y)`.
|
|
343
|
+
- `loadAudio(url)` → an `Audio` element; call `sound.play()`.
|
|
344
|
+
- `fetchJson(url)` → `{ok, status, data, text, parseError}` — never throws on a
|
|
345
|
+
bad status; check `ok`.
|
|
346
|
+
- `fetchBytes(url)` → `{ok, status, data: Uint8Array}` for binary payloads.
|
|
347
|
+
- `readDataUrl(file)` → a `data:` URL string for a `File` (from
|
|
348
|
+
`droppedFiles(event)` or a file input) — feed it straight to `loadImage`.
|
|
349
|
+
|
|
350
|
+
For an `Image` you own, use `new Image()` and `spriteSheet.src becomes "img.png"`.
|
|
351
|
+
|
|
352
|
+
Start the scene **after** assets are ready, or the first frame draws a blank
|
|
353
|
+
flash — gate scene start on a loaded flag. Sprite atlases are one image plus a
|
|
354
|
+
`fetchJson` manifest of `{x, y, w, h}` frames, drawn with
|
|
355
|
+
`drawImage(sheet, sx, sy, sw, sh, dx, dy, dw, dh)`.
|
|
356
|
+
|
|
357
|
+
---
|
|
358
|
+
|
|
359
|
+
## 8. Audio
|
|
360
|
+
|
|
361
|
+
```plainscript
|
|
362
|
+
remember ctx as audioContext()
|
|
363
|
+
playTone(440, 0.25)
|
|
364
|
+
remember sfx as loadAudio("boing.mp3")
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
`audioContext()` lazily creates a singleton `AudioContext` (with a
|
|
368
|
+
`webkitAudioContext` fallback); `playTone(freq, seconds, options)` plays a tone
|
|
369
|
+
on it. **Browsers require a user gesture to start audio** — the context stays
|
|
370
|
+
`"suspended"` until a click/keypress/touch, so resume it from the first one:
|
|
371
|
+
|
|
372
|
+
```plainscript
|
|
373
|
+
make resumeAudio()
|
|
374
|
+
ctx.resume()
|
|
375
|
+
done
|
|
376
|
+
document.addEventListener("click", resumeAudio)
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
The #1 "audio does not work" bug in browser games — always wire the resume.
|
|
380
|
+
|
|
381
|
+
---
|
|
382
|
+
|
|
383
|
+
## 9. Game state
|
|
384
|
+
|
|
385
|
+
Model entities and global values with record kinds; keep one `state` record so
|
|
386
|
+
the loop, HUD, and restart logic read one source of truth:
|
|
387
|
+
|
|
388
|
+
```plainscript
|
|
389
|
+
define a kind called "Player" with
|
|
390
|
+
x is 0
|
|
391
|
+
y is 0
|
|
392
|
+
lives is 3
|
|
393
|
+
done
|
|
394
|
+
|
|
395
|
+
define a kind called "GameState" with
|
|
396
|
+
score is 0
|
|
397
|
+
paused is false
|
|
398
|
+
done
|
|
399
|
+
|
|
400
|
+
remember state as create a GameState with score 0 and paused false
|
|
401
|
+
remember player as create a Player with x 320 and y 240
|
|
402
|
+
|
|
403
|
+
make resetGame()
|
|
404
|
+
state.score becomes 0
|
|
405
|
+
player.x becomes 320
|
|
406
|
+
player.y becomes 240
|
|
407
|
+
done
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
One-writer rule: **the loop applies, handlers register intent.** Input,
|
|
411
|
+
collision, and timers funnel through the loop's `step`, so state changes in
|
|
412
|
+
one predictable place per frame.
|
|
413
|
+
|
|
414
|
+
---
|
|
415
|
+
|
|
416
|
+
## 10. Collision and physics
|
|
417
|
+
|
|
418
|
+
Two workhorse tests. AABB — exact enough for rectangles and tiles:
|
|
419
|
+
|
|
420
|
+
```plainscript
|
|
421
|
+
if enemy.x is at least player.x - 26 and enemy.x is at most player.x + 26 and enemy.y is at least player.y - 26 and enemy.y is at most player.y + 26
|
|
422
|
+
state.score becomes state.score + 1
|
|
423
|
+
done
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
Circle distance — compare squared distance against squared radius to skip a
|
|
427
|
+
`Math.sqrt` per pair:
|
|
428
|
+
|
|
429
|
+
```plainscript
|
|
430
|
+
remember dx as enemy.x - player.x
|
|
431
|
+
remember dy as enemy.y - player.y
|
|
432
|
+
remember distSq as dx * dx + dy * dy
|
|
433
|
+
if distSq is less than 400
|
|
434
|
+
show "hit"
|
|
435
|
+
done
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
With many entities, do a broad phase first (bounding boxes, tile-grid buckets)
|
|
439
|
+
and run the precise test only on candidates. When you need real physics —
|
|
440
|
+
impulses, joints, continuous collision — delegate to a physics library. That is
|
|
441
|
+
interop, not surrender:
|
|
442
|
+
|
|
443
|
+
```plainscript
|
|
444
|
+
use matter
|
|
445
|
+
remember engine as matter.Engine.create()
|
|
446
|
+
remember world as engine.world
|
|
447
|
+
remember box as matter.Bodies.rectangle(320, 200, 40, 40)
|
|
448
|
+
matter.Composite.add(world, box)
|
|
449
|
+
|
|
450
|
+
make tick(dt)
|
|
451
|
+
matter.Engine.update(engine, 1000 * dt)
|
|
452
|
+
done
|
|
453
|
+
|
|
454
|
+
every frame
|
|
455
|
+
tick(1 / 60)
|
|
456
|
+
done
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
`use matter` binds the lowercase package name, so the chain is
|
|
460
|
+
`matter.Engine.create()`. The simulation policy stays in PlainScript; the
|
|
461
|
+
library computes physics.
|
|
462
|
+
|
|
463
|
+
---
|
|
464
|
+
|
|
465
|
+
## 11. UI overlay via DOM
|
|
466
|
+
|
|
467
|
+
Canvas = the world; DOM = the chrome. Score, lives, menus, and buttons live in
|
|
468
|
+
HTML and update by property assignment — `innerHTML becomes`,
|
|
469
|
+
`textContent becomes`, `classList.add`. Do not build UI in canvas when a div
|
|
470
|
+
will do:
|
|
471
|
+
|
|
472
|
+
```plainscript
|
|
473
|
+
remember scoreBox as document.querySelector("#score")
|
|
474
|
+
remember hud as parseHTML("<div id='hud'>Score: 0</div>")
|
|
475
|
+
document.body.appendChild(hud)
|
|
476
|
+
|
|
477
|
+
make refreshHud(scoreValue)
|
|
478
|
+
scoreBox.innerHTML becomes `Score: ${scoreValue}`
|
|
479
|
+
done
|
|
480
|
+
|
|
481
|
+
when clickButton "click" happens
|
|
482
|
+
refreshHud(10)
|
|
483
|
+
done
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
`parseHTML(html)` returns a `DocumentFragment` you can append. Update HUD
|
|
487
|
+
elements when values change, not every frame.
|
|
488
|
+
|
|
489
|
+
---
|
|
490
|
+
|
|
491
|
+
## 12. Networking
|
|
492
|
+
|
|
493
|
+
Server side uses the existing WebSocket server statement:
|
|
494
|
+
|
|
495
|
+
```plainscript
|
|
496
|
+
websocket server on 8080
|
|
497
|
+
when socket connects
|
|
498
|
+
send socket "connected"
|
|
499
|
+
done
|
|
500
|
+
when socket sends message
|
|
501
|
+
broadcast message
|
|
502
|
+
done
|
|
503
|
+
done
|
|
504
|
+
```
|
|
505
|
+
|
|
506
|
+
Client opens a WebSocket with `new WebSocket(url)` and listens with the same
|
|
507
|
+
`when ... happens` form as DOM events:
|
|
508
|
+
|
|
509
|
+
```plainscript
|
|
510
|
+
make applyState(data)
|
|
511
|
+
state.score becomes jsonDecode(data).score
|
|
512
|
+
done
|
|
513
|
+
|
|
514
|
+
remember ws as new WebSocket("wss://example.com/socket")
|
|
515
|
+
when ws "message" happens as e
|
|
516
|
+
applyState(e.data)
|
|
517
|
+
done
|
|
518
|
+
|
|
519
|
+
when ws "open" happens
|
|
520
|
+
webSocketSend(ws, {type: "join", name: "Ada"})
|
|
521
|
+
done
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
`webSocketSend(ws, value)` sends strings as-is and JSON-stringifies anything
|
|
525
|
+
else. Design around **authority**: one peer owns the simulation and broadcasts a
|
|
526
|
+
compact tick/snapshot; clients render and correct.
|
|
527
|
+
|
|
528
|
+
---
|
|
529
|
+
|
|
530
|
+
## 13. Persistence
|
|
531
|
+
|
|
532
|
+
`localStorage` is direct interop — strings only. Wrap state in JSON:
|
|
533
|
+
|
|
534
|
+
```plainscript
|
|
535
|
+
remember rawSave as localStorage.getItem("plainscript-save")
|
|
536
|
+
if rawSave is not null
|
|
537
|
+
remember restored as jsonDecode(rawSave)
|
|
538
|
+
state.score becomes restored.score
|
|
539
|
+
done
|
|
540
|
+
localStorage.setItem("plainscript-save", jsonEncode(state))
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
Save on meaningful changes or `beforeunload`, not every frame —
|
|
544
|
+
`localStorage` is synchronous and small (~5MB). For structured or large data,
|
|
545
|
+
wrap IndexedDB behind promises via the `idb` npm library (`use idb`).
|
|
546
|
+
|
|
547
|
+
---
|
|
548
|
+
|
|
549
|
+
## 14. Performance guidelines
|
|
550
|
+
|
|
551
|
+
- **One rAF loop, one `step(dt)`.** No scattered timers drawing or simulating
|
|
552
|
+
independently.
|
|
553
|
+
- **No allocations in the loop.** Reuse typed arrays and mutating math
|
|
554
|
+
(gl-matrix `mat4.rotateX(mat, mat, 0.5)`) — never fresh arrays per frame.
|
|
555
|
+
- **Cap dt** so a background-tab resume cannot run the sim forward for seconds.
|
|
556
|
+
- **Canvas sizing discipline.** Match backing size to display size — oversized
|
|
557
|
+
canvases are the #1 silent frame-rate killer.
|
|
558
|
+
- **Reuse sprites and draw calls**; redraw only what changed.
|
|
559
|
+
- **No synchronous work in the loop.** No storage writes, no fetch, no heavy
|
|
560
|
+
JSON per frame.
|
|
561
|
+
- **Keep event handlers thin.** Set a flag; the loop works.
|
|
562
|
+
|
|
563
|
+
```plainscript
|
|
564
|
+
remember verts as new Float32Array(64)
|
|
565
|
+
make refreshVerts()
|
|
566
|
+
for index i from 0 to 15
|
|
567
|
+
verts[i] becomes verts[i] * 2
|
|
568
|
+
done
|
|
569
|
+
done
|
|
570
|
+
refreshVerts()
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
---
|
|
574
|
+
|
|
575
|
+
## 15. JavaScript interoperability
|
|
576
|
+
|
|
577
|
+
What an imported library needs, without leaving PlainScript.
|
|
578
|
+
|
|
579
|
+
**Import npm packages and local modules:**
|
|
580
|
+
|
|
581
|
+
```plainscript
|
|
582
|
+
use lodash
|
|
583
|
+
bring axios from "axios"
|
|
584
|
+
bring geometry from "./helpers.pln"
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
**Call member chains** — no special syntax:
|
|
588
|
+
|
|
589
|
+
```plainscript
|
|
590
|
+
crypto.createHash("sha256").update("abc").digest("hex")
|
|
591
|
+
mesh.scale.set(2, 2, 2)
|
|
592
|
+
```
|
|
593
|
+
|
|
594
|
+
**Construct with `new Type(args)`** — statement start, `remember`, arguments,
|
|
595
|
+
member chains, or bare without parens:
|
|
596
|
+
|
|
597
|
+
```plainscript
|
|
598
|
+
remember date as new Date().getTime()
|
|
599
|
+
remember mut as new THREE.Vector3(1, 2, 3)
|
|
600
|
+
remember vec as new Float32Array([0.5, 1.0, 1.5])
|
|
601
|
+
scene.add(new THREE.Mesh(geometry, material))
|
|
602
|
+
remember box as new Enemy
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
**Pass `make`-function references as callbacks:**
|
|
606
|
+
|
|
607
|
+
```plainscript
|
|
608
|
+
make fitWindow()
|
|
609
|
+
camera.aspect becomes window.innerWidth / window.innerHeight
|
|
610
|
+
camera.updateProjectionMatrix()
|
|
611
|
+
done
|
|
612
|
+
window.addEventListener("resize", fitWindow)
|
|
613
|
+
button.onclick becomes fitWindow
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
**Promises** — browser builtins (`loadImage`, `fetchJson`, `loadAudio`)
|
|
617
|
+
auto-await. Raw interop uses `await` / `wait for`; errors use the repository's
|
|
618
|
+
`try/recover` idiom — never `.then`:
|
|
619
|
+
|
|
620
|
+
```plainscript
|
|
621
|
+
remember response as await fetch("/api/state")
|
|
622
|
+
remember data as await response.json()
|
|
623
|
+
show data
|
|
624
|
+
|
|
625
|
+
try
|
|
626
|
+
remember scores as wait for fetchJson("/api/scores")
|
|
627
|
+
show scores
|
|
628
|
+
recover as err
|
|
629
|
+
show message of err
|
|
630
|
+
finally
|
|
631
|
+
show "done"
|
|
632
|
+
```
|
|
633
|
+
|
|
634
|
+
**Typed arrays / binary** — `remember buffer as new Uint8Array(64)` and index
|
|
635
|
+
with `buffer[0] becomes 255`.
|
|
636
|
+
|
|
637
|
+
**Arrays, objects, JSON:**
|
|
638
|
+
|
|
639
|
+
```plainscript
|
|
640
|
+
remember people as [{name: "Ada"}, {name: "Grace"}]
|
|
641
|
+
for each person in people
|
|
642
|
+
show person.name
|
|
643
|
+
done
|
|
644
|
+
remember config as jsonDecode(rawJson)
|
|
645
|
+
```
|
|
646
|
+
|
|
647
|
+
Rules: no `=>`, `.then`, `let/const`, braces, or semicolons in `.pln`. A
|
|
648
|
+
library is *called* from PlainScript — symbol, flow, and state stay in
|
|
649
|
+
PlainScript. Need a stateful callback? Define a `make` function that reads the
|
|
650
|
+
shared state you already have.
|
|
651
|
+
|
|
652
|
+
---
|
|
653
|
+
|
|
654
|
+
## 16. Generated JavaScript expectations
|
|
655
|
+
|
|
656
|
+
What the compiler emits for a game, so you can read and debug `public/game.js`:
|
|
657
|
+
|
|
658
|
+
- Declarations emit as `let`/`const`; functions as `function name(...)`.
|
|
659
|
+
- `when <target> "<event>" happens` → `target.addEventListener("event", function (event) { ... })`.
|
|
660
|
+
- `every frame ... done` → a self-scheduling
|
|
661
|
+
`requestAnimationFrame(function __frame(t) { ... })`; `after 3 seconds ... done`
|
|
662
|
+
→ `setTimeout(..., 3 * 1000)`.
|
|
663
|
+
- Any top-level `await` (triggered by promise builtins like `loadImage`) wraps
|
|
664
|
+
the program in `(async () => { ... })();`; in-handler awaits make only that
|
|
665
|
+
handler `async`.
|
|
666
|
+
- `require()` appears **only** for `use <pkg>` / `bring name from "pkg"`.
|
|
667
|
+
- The file ends with a guarded tail
|
|
668
|
+
(`if (typeof module !== 'undefined') { module.exports = { ... }; }`) so the
|
|
669
|
+
same output is a harmless browser script and still works under Node.
|
|
670
|
+
|
|
671
|
+
Debug by checking `game.js` for that shape (`addEventListener`,
|
|
672
|
+
`requestAnimationFrame`, the IIFE), not your source indentation.
|
|
673
|
+
|
|
674
|
+
---
|
|
675
|
+
|
|
676
|
+
## 17. Common mistakes
|
|
677
|
+
|
|
678
|
+
| Mistake | Correct response |
|
|
679
|
+
| --- | --- |
|
|
680
|
+
| `while true` loop for the game loop | `requestAnimationFrame` / `every frame` |
|
|
681
|
+
| Mutating the world inside an event handler | Set a `keys{}` flag; the loop applies it |
|
|
682
|
+
| No delta time (speed varies with frame rate) | `dt = (t - last) / 1000`, multiply speeds by `dt` |
|
|
683
|
+
| `.then(...)` on a promise | `await` / `wait for`; `try/recover` for errors |
|
|
684
|
+
| Treating `check` as a run | `check` validates; `build`, then open the page to run |
|
|
685
|
+
| Blocking `fetch` in the browser | `await fetch`, `fetchJson`, or `loadImage` |
|
|
686
|
+
| Variable named for a keyword/builtin | Rename (`start`, `now`, `get`, `set`, `reply`, `from`, `as`, `of`, `in`, `json`, `bytes`, `update`, `status` are taken) |
|
|
687
|
+
| Writing `is most` for `<=` | Use `is at most` (`is most` is not a comparison) |
|
|
688
|
+
| Storing colors as opaque decimals (`4244579`) | Hex literal `0x40c463` is supported (or a `"#40c463"` string) |
|
|
689
|
+
| `make update` / `make get` as function names | Rename — those are keywords |
|
|
690
|
+
| Bare `keys["ArrowLeft"]` in `if` | Compare: `if keys["ArrowLeft"] is true` |
|
|
691
|
+
| Audio with no user gesture | `ctx.resume()` from a click/keydown handler |
|
|
692
|
+
| Drawing before assets load | Gate scene start on a loaded flag |
|
|
693
|
+
|
|
694
|
+
---
|
|
695
|
+
|
|
696
|
+
## 18. Complete working examples
|
|
697
|
+
|
|
698
|
+
### 18.1 A full 2D game in one file
|
|
699
|
+
|
|
700
|
+
Player + falling enemies + score + collision + DOM HUD + restart. The canonical
|
|
701
|
+
shape to copy: kinds and state up top, handlers only record input, the loop
|
|
702
|
+
owns all movement, canvas draws the world, DOM shows the score.
|
|
703
|
+
|
|
704
|
+
```plainscript
|
|
705
|
+
define a kind called "Player" with
|
|
706
|
+
x is 0
|
|
707
|
+
y is 0
|
|
708
|
+
r is 12
|
|
709
|
+
speed is 240
|
|
710
|
+
done
|
|
711
|
+
define a kind called "Enemy" with
|
|
712
|
+
x is 0
|
|
713
|
+
y is 0
|
|
714
|
+
speed is 0
|
|
715
|
+
done
|
|
716
|
+
|
|
717
|
+
remember canvas as document.getElementById("game")
|
|
718
|
+
remember ctx as canvas.getContext("2d")
|
|
719
|
+
remember state as {score: 0, over: false}
|
|
720
|
+
remember keys as {}
|
|
721
|
+
|
|
722
|
+
when document "keydown" happens as ke
|
|
723
|
+
keys[ke.key] becomes true
|
|
724
|
+
done
|
|
725
|
+
|
|
726
|
+
when document "keyup" happens as ke
|
|
727
|
+
keys[ke.key] becomes false
|
|
728
|
+
done
|
|
729
|
+
|
|
730
|
+
remember player as create a Player with x 320 and y 460
|
|
731
|
+
remember enemies as [
|
|
732
|
+
{x: 60, y: 60, speed: 110},
|
|
733
|
+
{x: 200, y: 60, speed: 140},
|
|
734
|
+
{x: 340, y: 60, speed: 90},
|
|
735
|
+
{x: 480, y: 60, speed: 160},
|
|
736
|
+
{x: 560, y: 60, speed: 120}
|
|
737
|
+
]
|
|
738
|
+
|
|
739
|
+
make reset()
|
|
740
|
+
state.score becomes 0
|
|
741
|
+
state.over becomes false
|
|
742
|
+
player.x becomes 320
|
|
743
|
+
player.y becomes 460
|
|
744
|
+
for each enemy in enemies
|
|
745
|
+
enemy.y becomes 60
|
|
746
|
+
done
|
|
747
|
+
done
|
|
748
|
+
|
|
749
|
+
when document.getElementById("restart") "click" happens
|
|
750
|
+
reset()
|
|
751
|
+
done
|
|
752
|
+
|
|
753
|
+
make step(dt)
|
|
754
|
+
if state.over is false
|
|
755
|
+
if keys["ArrowLeft"] is true
|
|
756
|
+
player.x becomes player.x - player.speed * dt
|
|
757
|
+
done
|
|
758
|
+
if keys["ArrowRight"] is true
|
|
759
|
+
player.x becomes player.x + player.speed * dt
|
|
760
|
+
done
|
|
761
|
+
for each enemy in enemies
|
|
762
|
+
enemy.y becomes enemy.y + enemy.speed * dt
|
|
763
|
+
if enemy.y is above 480
|
|
764
|
+
enemy.y becomes 40
|
|
765
|
+
enemy.x becomes 40 + 560 * Math.random()
|
|
766
|
+
state.score becomes state.score + 1
|
|
767
|
+
done
|
|
768
|
+
if enemy.x is at least player.x - 26 and enemy.x is at most player.x + 26 and enemy.y is at least player.y - 26 and enemy.y is at most player.y + 26
|
|
769
|
+
state.over becomes true
|
|
770
|
+
done
|
|
771
|
+
done
|
|
772
|
+
done
|
|
773
|
+
ctx.clearRect(0, 0, 640, 480)
|
|
774
|
+
ctx.fillStyle becomes "#1b1e24"
|
|
775
|
+
ctx.fillRect(0, 0, 640, 480)
|
|
776
|
+
for each enemy in enemies
|
|
777
|
+
ctx.fillStyle becomes "#e2543f"
|
|
778
|
+
ctx.beginPath()
|
|
779
|
+
ctx.arc(enemy.x, enemy.y, 10, 0, Math.PI * 2)
|
|
780
|
+
ctx.fill()
|
|
781
|
+
done
|
|
782
|
+
ctx.fillStyle becomes "#40c463"
|
|
783
|
+
ctx.beginPath()
|
|
784
|
+
ctx.arc(player.x, player.y, player.r, 0, Math.PI * 2)
|
|
785
|
+
ctx.fill()
|
|
786
|
+
document.getElementById("score").textContent becomes `Score: ${state.score}`
|
|
787
|
+
if state.over is true
|
|
788
|
+
ctx.fillStyle becomes "#fff"
|
|
789
|
+
ctx.fillText("GAME OVER - press Restart", 200, 240)
|
|
790
|
+
done
|
|
791
|
+
done
|
|
792
|
+
|
|
793
|
+
make loop(t)
|
|
794
|
+
requestAnimationFrame(loop)
|
|
795
|
+
step(t / 1000)
|
|
796
|
+
done
|
|
797
|
+
requestAnimationFrame(loop)
|
|
798
|
+
```
|
|
799
|
+
|
|
800
|
+
### 18.2 A full 3D scene in one file
|
|
801
|
+
|
|
802
|
+
A camera, renderer, and one rotating mesh driven from one rAF loop, using a
|
|
803
|
+
global `THREE` from a CDN script tag:
|
|
804
|
+
|
|
805
|
+
```plainscript
|
|
806
|
+
remember scene as new THREE.Scene()
|
|
807
|
+
remember camera as new THREE.PerspectiveCamera(75, 640 / 480, 0.1, 1000)
|
|
808
|
+
remember renderer as new THREE.WebGLRenderer({antialias: true})
|
|
809
|
+
renderer.setSize(640, 480)
|
|
810
|
+
document.getElementById("stage").appendChild(renderer.domElement)
|
|
811
|
+
|
|
812
|
+
remember geometry as new THREE.BoxGeometry(1, 1, 1)
|
|
813
|
+
remember material as new THREE.MeshStandardMaterial({color: 0x40c463})
|
|
814
|
+
remember mesh as new THREE.Mesh(geometry, material)
|
|
815
|
+
scene.add(mesh)
|
|
816
|
+
camera.position.set(0, 0, 5)
|
|
817
|
+
|
|
818
|
+
make loop()
|
|
819
|
+
mesh.rotation.x becomes mesh.rotation.x + 0.01
|
|
820
|
+
mesh.rotation.y becomes mesh.rotation.y + 0.01
|
|
821
|
+
renderer.render(scene, camera)
|
|
822
|
+
requestAnimationFrame(loop)
|
|
823
|
+
done
|
|
824
|
+
requestAnimationFrame(loop)
|
|
825
|
+
```
|
|
826
|
+
|
|
827
|
+
---
|
|
828
|
+
|
|
829
|
+
## 19. Recommended architecture
|
|
830
|
+
|
|
831
|
+
### 19.1 Small games
|
|
832
|
+
|
|
833
|
+
For games up to a few hundred lines, one `.pln` file is correct: one `state`
|
|
834
|
+
record owned by the loop, one rAF loop (`every frame` or the dt form) that
|
|
835
|
+
steps then draws, one input set (a `keys{}` map plus one pointer handler), and
|
|
836
|
+
plain DOM updates for the HUD. File count should track surface area — a small
|
|
837
|
+
game in five files is as wrong as a big game in one.
|
|
838
|
+
|
|
839
|
+
### 19.2 Large games
|
|
840
|
+
|
|
841
|
+
Split by responsibility, not by function. The entry file owns lifecycle (and
|
|
842
|
+
the server); modules own entities and systems:
|
|
843
|
+
|
|
844
|
+
```plainscript
|
|
845
|
+
bring spawnEnemy from "./entities.pln"
|
|
846
|
+
import { loadAssets } from "./assets.pln"
|
|
847
|
+
|
|
848
|
+
remember firstWave as spawnEnemy(320, 40)
|
|
849
|
+
```
|
|
850
|
+
|
|
851
|
+
A proven structure:
|
|
852
|
+
|
|
853
|
+
- **Entity factories** — `define a kind` plus a `make spawnThing()` returning a
|
|
854
|
+
new instance; one file per entity family.
|
|
855
|
+
- **Systems as `make` functions** — one system (movement, collision, rendering,
|
|
856
|
+
scoring) per function, run in order by the loop.
|
|
857
|
+
- **Scene/state table** — a state record or switch with explicit `attract`,
|
|
858
|
+
`play`, and `gameover` states.
|
|
859
|
+
- **Asset manifest** — one `assets` record of URLs loaded at boot; scenes look
|
|
860
|
+
up paths instead of hardcoding.
|
|
861
|
+
- **A server when networking** — own `server.pln` with `websocket server`,
|
|
862
|
+
authority checks, and snapshot broadcasts; the client is a pure renderer +
|
|
863
|
+
input reporter.
|
|
864
|
+
|
|
865
|
+
Entities are records, factories and systems are PlainScript functions; browser
|
|
866
|
+
APIs stay libraries you call.
|
|
867
|
+
|
|
868
|
+
---
|
|
869
|
+
|
|
870
|
+
## 20. DO list and DO-NOT list
|
|
871
|
+
|
|
872
|
+
| DO | DO-NOT |
|
|
873
|
+
| --- | --- |
|
|
874
|
+
| Write the game logic in PlainScript | Rewrite logic in JS "because the API is JS" |
|
|
875
|
+
| Run `node compiler/cli.js check <file.pln>` before claiming it works | Claim code works because it looks readable |
|
|
876
|
+
| Use one rAF loop for the whole frame | `while true` / synchronous loops |
|
|
877
|
+
| Record input in handlers, apply in the loop | Mutate world state inside events |
|
|
878
|
+
| Multiply speeds by delta time | Move a fixed amount per frame |
|
|
879
|
+
| Use `await` / `wait for` and `try/recover` | `.then` / `.catch` chains |
|
|
880
|
+
| Keep handlers and per-frame work small | Heavy work, storage writes, fetches in the loop |
|
|
881
|
+
| Reuse buffers and objects across frames | Allocate new arrays every frame |
|
|
882
|
+
| Gate scene start on loaded assets | Draw before textures/audio are ready |
|
|
883
|
+
| Resume audio from a user gesture | Start audio and wonder why it is silent |
|
|
884
|
+
| Call libraries through interop | Hand-write what a library already does |
|
|
885
|
+
|
|
886
|
+
---
|
|
887
|
+
|
|
888
|
+
## Appendix A: Canonical snippets quick reference
|
|
889
|
+
|
|
890
|
+
Every line below is verified canonical form — copy it exactly:
|
|
891
|
+
|
|
892
|
+
```plainscript
|
|
893
|
+
remember canvas as document.getElementById("game")
|
|
894
|
+
remember ctx as canvas.getContext("2d")
|
|
895
|
+
remember s as new THREE.Scene()
|
|
896
|
+
when document "keydown" happens as ke
|
|
897
|
+
show ke.key
|
|
898
|
+
done
|
|
899
|
+
every frame
|
|
900
|
+
ctx.clearRect(0, 0, 640, 480)
|
|
901
|
+
done
|
|
902
|
+
after 0.5 seconds
|
|
903
|
+
show "tick"
|
|
904
|
+
done
|
|
905
|
+
remember bg as loadImage("img.png")
|
|
906
|
+
```
|
|
907
|
+
|
|
908
|
+
## Run it
|
|
909
|
+
|
|
910
|
+
Runnable, maintained reference implementations live in:
|
|
911
|
+
|
|
912
|
+
- `examples/canvas-game` — canvas 2D dodge game (keys map + `every frame` + delta time + kinds + restart).
|
|
913
|
+
- `examples/browser-interactive` — DOM-first interactive app (`when ... happens`, `classList`, innerHTML/textContent).
|
|
914
|
+
- `examples/three-dimensional` — WebGL 3D scene via the global `THREE` object.
|
|
915
|
+
- `examples/javascript-library` — an npm library (`bring THREE from "three"`), callbacks, and `fetchJson`.
|