create-clarity 0.2.0 → 0.5.0
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 +23 -2
- package/bin/create-clarity.js +26 -13
- package/lib/game.js +530 -0
- package/lib/templates.js +3 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,7 +18,7 @@ npm create clarity@latest
|
|
|
18
18
|
|
|
19
19
|
An interactive prompt lets you pick:
|
|
20
20
|
|
|
21
|
-
- **Template** — Basic (client-rendered SPA)
|
|
21
|
+
- **Template** — Basic (client-rendered SPA), SSR (server-side rendering + hydration) or Game (a small 3D game, see below)
|
|
22
22
|
- **Add-ons** — TypeScript, Router, i18n, Testing (any combination)
|
|
23
23
|
|
|
24
24
|
The generated project is a ready-to-run Vite app wired to the Clarity compiler,
|
|
@@ -36,7 +36,7 @@ npx create-clarity my-app -y # all defaults, no prompts
|
|
|
36
36
|
|
|
37
37
|
| Flag | Effect |
|
|
38
38
|
|------|--------|
|
|
39
|
-
| `--spa` / `--ssr` | choose template |
|
|
39
|
+
| `--spa` / `--ssr` / `--game` | choose template |
|
|
40
40
|
| `--ts`, `--typescript` | add TypeScript |
|
|
41
41
|
| `--router` | add the router |
|
|
42
42
|
| `--i18n` | add internationalization |
|
|
@@ -54,3 +54,24 @@ npm run dev
|
|
|
54
54
|
|
|
55
55
|
Zero runtime dependencies — `create-clarity` uses only Node built-ins, so it
|
|
56
56
|
starts instantly via `npm create` / `npx`.
|
|
57
|
+
|
|
58
|
+
## A game
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
npm create clarity@latest my-game -- --game
|
|
62
|
+
cd my-game && npm install
|
|
63
|
+
npm run dev # play it
|
|
64
|
+
npm test # the rules, played with no browser
|
|
65
|
+
npm run balance # 24 games on 24 seeds: how they went
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
A small 3D game that is whole, to change until it is yours:
|
|
69
|
+
|
|
70
|
+
- `src/rules.js`: the game itself, as plain numbers and chance from a seed. No page, no clock.
|
|
71
|
+
- `src/Game.clarity`: the page. A `<Scene>` from [`@clarity-js/gl`](https://www.npmjs.com/package/@clarity-js/gl)
|
|
72
|
+
bound to state, keys, a gamepad, an on-screen stick and tilt, sounds made from numbers by
|
|
73
|
+
[`@clarity-js/audio`](https://www.npmjs.com/package/@clarity-js/audio), a burst of particles.
|
|
74
|
+
- `test/rules.test.js`: six tests that play the rules in Node.
|
|
75
|
+
- An `ai:` contract, so an agent can play: `clarity.game().act('steer', 1, 0)`.
|
|
76
|
+
|
|
77
|
+
Built, the whole game is one script of about 44 KB gzipped. The add-on flags do not apply to it.
|
package/bin/create-clarity.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* npx create-clarity my-app --ssr --ts --router
|
|
8
8
|
*
|
|
9
9
|
* Flags (skip the matching prompt):
|
|
10
|
-
* --ssr / --spa
|
|
10
|
+
* --ssr / --spa / --game template (--game: a small 3D game with rules, tests, sound and input)
|
|
11
11
|
* --ts / --typescript TypeScript add-on
|
|
12
12
|
* --router router add-on
|
|
13
13
|
* --i18n i18n add-on
|
|
@@ -25,6 +25,8 @@ const { scaffold, isNonEmptyDir } = require('../lib/scaffold');
|
|
|
25
25
|
|
|
26
26
|
const c = prompts.colors;
|
|
27
27
|
const PKG_VERSION = require('../package.json').version;
|
|
28
|
+
// the versions a new project asks for (bumped with each release of the framework)
|
|
29
|
+
const VERSIONS = { clarity: '^0.17.0', gl: '^0.4.0', audio: '^0.1.0' };
|
|
28
30
|
|
|
29
31
|
function parseArgs(argv) {
|
|
30
32
|
const args = { _: [], flags: {} };
|
|
@@ -66,18 +68,24 @@ async function main() {
|
|
|
66
68
|
}
|
|
67
69
|
|
|
68
70
|
// ── Template ───────────────────────────────────────────────────────────────
|
|
69
|
-
let ssr;
|
|
70
|
-
if ('
|
|
71
|
+
let ssr = false, game = false;
|
|
72
|
+
if ('game' in argv.flags) game = true;
|
|
73
|
+
else if ('ssr' in argv.flags) ssr = true;
|
|
71
74
|
else if ('spa' in argv.flags) ssr = false;
|
|
72
|
-
else
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
75
|
+
else if (!yes) {
|
|
76
|
+
const picked = await prompts.select('Which template?', [
|
|
77
|
+
{ value: 'spa', label: 'Basic (SPA)', hint: 'client-rendered single-page app' },
|
|
78
|
+
{ value: 'ssr', label: 'SSR', hint: 'server-side rendering + hydration' },
|
|
79
|
+
{ value: 'game', label: 'Game (3D)', hint: 'rules, a 3D scene, input, sound and tests' },
|
|
80
|
+
], 0);
|
|
81
|
+
ssr = picked === 'ssr'; game = picked === 'game';
|
|
82
|
+
}
|
|
76
83
|
|
|
77
84
|
// ── Add-ons ────────────────────────────────────────────────────────────────
|
|
78
85
|
let addons;
|
|
79
86
|
const flagAddons = ['typescript', 'ts', 'router', 'i18n', 'testing'].some(f => f in argv.flags);
|
|
80
|
-
if (
|
|
87
|
+
if (game) addons = new Set(); // the game template stands alone: it brings its own tests
|
|
88
|
+
else if (flagAddons || yes) {
|
|
81
89
|
addons = new Set();
|
|
82
90
|
if (argv.flags.typescript || argv.flags.ts) addons.add('typescript');
|
|
83
91
|
if (argv.flags.router) addons.add('router');
|
|
@@ -94,13 +102,16 @@ async function main() {
|
|
|
94
102
|
}
|
|
95
103
|
|
|
96
104
|
// ── clarity-js dependency source ───────────────────────────────────────────
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
: `^0.12.0`;
|
|
105
|
+
const localRoot = argv.flags.local ? path.resolve(process.cwd(), argv.flags.local) : null;
|
|
106
|
+
const clarityDep = localRoot ? `file:${localRoot}` : VERSIONS.clarity;
|
|
100
107
|
|
|
101
108
|
const options = {
|
|
102
109
|
projectName,
|
|
103
110
|
ssr,
|
|
111
|
+
game,
|
|
112
|
+
localRoot,
|
|
113
|
+
glDep: VERSIONS.gl,
|
|
114
|
+
audioDep: VERSIONS.audio,
|
|
104
115
|
typescript: addons.has('typescript'),
|
|
105
116
|
router: addons.has('router'),
|
|
106
117
|
i18n: addons.has('i18n'),
|
|
@@ -118,12 +129,14 @@ async function main() {
|
|
|
118
129
|
options.i18n && 'i18n',
|
|
119
130
|
options.testing && 'Testing',
|
|
120
131
|
].filter(Boolean);
|
|
121
|
-
console.log(` ${c.gray}template:${c.reset} ${ssr ? 'SSR' : 'Basic (SPA)'}${addonList.length ? ` ${c.gray}add-ons:${c.reset} ${addonList.join(', ')}` : ''}`);
|
|
132
|
+
console.log(` ${c.gray}template:${c.reset} ${game ? 'Game (3D)' : ssr ? 'SSR' : 'Basic (SPA)'}${addonList.length ? ` ${c.gray}add-ons:${c.reset} ${addonList.join(', ')}` : ''}`);
|
|
122
133
|
|
|
123
134
|
console.log(`\n${c.bold}Next steps:${c.reset}`);
|
|
124
135
|
console.log(` cd ${projectName}`);
|
|
125
136
|
console.log(` npm install`);
|
|
126
|
-
console.log(` npm run dev
|
|
137
|
+
console.log(` npm run dev${game ? ` ${c.gray}# play it${c.reset}` : ''}`);
|
|
138
|
+
if (game) { console.log(` npm test ${c.gray}# the rules, played with no browser${c.reset}`); console.log(` npm run balance ${c.gray}# many games on many seeds${c.reset}`); }
|
|
139
|
+
console.log('');
|
|
127
140
|
}
|
|
128
141
|
|
|
129
142
|
main().catch(err => {
|
package/lib/game.js
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The game template: `npm create clarity -- --game`.
|
|
3
|
+
*
|
|
4
|
+
* A small 3D game that is whole: rules kept apart from the page (so they are tested and balanced
|
|
5
|
+
* with no browser), a scene drawn by @clarity-js/gl, keys, gamepad, an on-screen stick and tilt,
|
|
6
|
+
* sound from @clarity-js/audio, particles, and a contract an AI agent can play it through.
|
|
7
|
+
* It is a starting point to change, not a framework to learn.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
'use strict';
|
|
11
|
+
|
|
12
|
+
function gameFiles(opts) {
|
|
13
|
+
const files = {};
|
|
14
|
+
const local = opts.localRoot ? (name) => `file:${opts.localRoot}/packages/${name}` : null;
|
|
15
|
+
|
|
16
|
+
files['package.json'] = JSON.stringify({
|
|
17
|
+
name: opts.projectName,
|
|
18
|
+
private: true,
|
|
19
|
+
version: '0.0.0',
|
|
20
|
+
type: 'module',
|
|
21
|
+
scripts: {
|
|
22
|
+
dev: 'vite',
|
|
23
|
+
build: 'vite build',
|
|
24
|
+
preview: 'vite preview',
|
|
25
|
+
test: 'node --test',
|
|
26
|
+
balance: 'clarity balance src/rules.js --seeds 24 --seconds 150',
|
|
27
|
+
},
|
|
28
|
+
dependencies: {
|
|
29
|
+
'@ozsarman/clarityjs': opts.clarityDep,
|
|
30
|
+
'@clarity-js/gl': local ? local('clarity-gl') : opts.glDep,
|
|
31
|
+
'@clarity-js/audio': local ? local('clarity-audio') : opts.audioDep,
|
|
32
|
+
},
|
|
33
|
+
devDependencies: { vite: '^5.0.0' },
|
|
34
|
+
}, null, 2) + '\n';
|
|
35
|
+
|
|
36
|
+
files['vite.config.js'] =
|
|
37
|
+
`import { defineConfig } from 'vite';
|
|
38
|
+
import clarity from '@ozsarman/clarityjs/vite';
|
|
39
|
+
|
|
40
|
+
export default defineConfig({
|
|
41
|
+
plugins: [clarity()],
|
|
42
|
+
// one copy of the runtime, whoever asks for it (the renderer does too): state made in one place is seen in the other
|
|
43
|
+
resolve: { dedupe: ['@ozsarman/clarityjs'] },
|
|
44
|
+
});
|
|
45
|
+
`;
|
|
46
|
+
|
|
47
|
+
files['index.html'] =
|
|
48
|
+
`<!DOCTYPE html>
|
|
49
|
+
<html lang="en">
|
|
50
|
+
<head>
|
|
51
|
+
<meta charset="UTF-8" />
|
|
52
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, user-scalable=no" />
|
|
53
|
+
<meta name="theme-color" content="#0b1020" />
|
|
54
|
+
<title>${opts.projectName}</title>
|
|
55
|
+
<link rel="stylesheet" href="/src/styles.css" />
|
|
56
|
+
</head>
|
|
57
|
+
<body>
|
|
58
|
+
<div id="app"></div>
|
|
59
|
+
<script type="module" src="/src/main.js"></script>
|
|
60
|
+
</body>
|
|
61
|
+
</html>
|
|
62
|
+
`;
|
|
63
|
+
|
|
64
|
+
files['src/main.js'] =
|
|
65
|
+
`import { mount } from '@ozsarman/clarityjs';
|
|
66
|
+
import { aiDiscover } from '@ozsarman/clarityjs/runtime';
|
|
67
|
+
import { clock } from '@ozsarman/clarityjs/game-loop';
|
|
68
|
+
import { connectAgent } from '@ozsarman/clarityjs/agent';
|
|
69
|
+
import { describeView } from '@clarity-js/gl';
|
|
70
|
+
import { Game } from './Game.clarity';
|
|
71
|
+
|
|
72
|
+
mount(Game, document.getElementById('app'));
|
|
73
|
+
|
|
74
|
+
// A door for you, in the console:
|
|
75
|
+
// clarity.game().act('start'); clarity.game().act('steer', 1, 0); clarity.game().read('score')
|
|
76
|
+
// clarity.clock.pause(); clarity.clock.step(1 / 60)
|
|
77
|
+
globalThis.clarity = { aiDiscover, clock, game: () => aiDiscover().find((c) => c.component === 'Game') ?? null };
|
|
78
|
+
|
|
79
|
+
// And one for an AI agent (Claude Code, Claude Desktop, Cursor …), over MCP:
|
|
80
|
+
// npx clarity mcp --open http://localhost:5173
|
|
81
|
+
// It does nothing unless the page is opened with ?agent in its address, which that command does.
|
|
82
|
+
connectAgent({ view: () => describeView(document.querySelector('.game-scene')) });
|
|
83
|
+
`;
|
|
84
|
+
|
|
85
|
+
files['src/styles.css'] = STYLES;
|
|
86
|
+
files['src/rules.js'] = RULES;
|
|
87
|
+
files['src/Game.clarity'] = GAME;
|
|
88
|
+
files['test/rules.test.js'] = TEST;
|
|
89
|
+
files['README.md'] = readme(opts);
|
|
90
|
+
files['.gitignore'] = 'node_modules\ndist\n.DS_Store\n*.local\n';
|
|
91
|
+
return files;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ─── the rules ──────────────────────────────────────────────────────────────────
|
|
95
|
+
|
|
96
|
+
const RULES = `// The rules of the game, and nothing else: plain numbers, chance from a seed, no page and no clock.
|
|
97
|
+
// The page (Game.clarity) shows what report() says and passes on what the player does. Because the
|
|
98
|
+
// rules stand alone, they run the same in a browser, in \`npm test\` and under \`npm run balance\`,
|
|
99
|
+
// and the same seed always plays the same game.
|
|
100
|
+
|
|
101
|
+
import { createSim } from '@ozsarman/clarityjs/sim'
|
|
102
|
+
|
|
103
|
+
/** Half the side of the square field. */
|
|
104
|
+
export const FIELD = 6
|
|
105
|
+
const SPEED = 6.5 // how fast the player goes at full tilt
|
|
106
|
+
const REACH = 0.85 // how near a spark must be to be caught
|
|
107
|
+
const SHARDS_EVERY = 6 // another shard joins every so many sparks
|
|
108
|
+
|
|
109
|
+
const clamp = (v, a, b) => (v < a ? a : v > b ? b : v)
|
|
110
|
+
const far = (a, b) => Math.hypot(a.x - b.x, a.z - b.z)
|
|
111
|
+
|
|
112
|
+
// somewhere on the field that is not right on top of the player
|
|
113
|
+
function somewhere(rng, player, least = 2.5) {
|
|
114
|
+
for (let i = 0; i < 20; i++) {
|
|
115
|
+
const at = { x: rng.range(-FIELD + 0.6, FIELD - 0.6), z: rng.range(-FIELD + 0.6, FIELD - 0.6) }
|
|
116
|
+
if (far(at, player) >= least) return at
|
|
117
|
+
}
|
|
118
|
+
return { x: -player.x, z: -player.z }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export const createGame = ({ seed = 1 } = {}) => createSim({
|
|
122
|
+
seed,
|
|
123
|
+
setup: () => ({ status: 'ready', score: 0, best: 0, lives: 3, shield: 0, ids: 0, player: { x: 0, z: 0, vx: 0, vz: 0 }, steer: { x: 0, z: 0 }, sparks: [], shards: [] }),
|
|
124
|
+
|
|
125
|
+
step(s, dt, { rng, emit }) {
|
|
126
|
+
if (s.status !== 'playing') return
|
|
127
|
+
const p = s.player
|
|
128
|
+
// the player eases towards where it is steered, and stays on the field
|
|
129
|
+
let ix = s.steer.x, iz = s.steer.z
|
|
130
|
+
const len = Math.hypot(ix, iz)
|
|
131
|
+
if (len > 1) { ix /= len; iz /= len }
|
|
132
|
+
const k = Math.min(1, dt * 9)
|
|
133
|
+
p.vx += (ix * SPEED - p.vx) * k
|
|
134
|
+
p.vz += (iz * SPEED - p.vz) * k
|
|
135
|
+
p.x = clamp(p.x + p.vx * dt, -FIELD, FIELD)
|
|
136
|
+
p.z = clamp(p.z + p.vz * dt, -FIELD, FIELD)
|
|
137
|
+
if (s.shield > 0) s.shield = Math.max(0, s.shield - dt)
|
|
138
|
+
|
|
139
|
+
// sparks: catch one and another appears somewhere else; every few, the field gets more dangerous
|
|
140
|
+
for (const spark of s.sparks) {
|
|
141
|
+
if (far(spark, p) > REACH) continue
|
|
142
|
+
s.score++
|
|
143
|
+
emit({ type: 'spark', x: spark.x, z: spark.z, score: s.score })
|
|
144
|
+
Object.assign(spark, somewhere(rng, p), { id: ++s.ids })
|
|
145
|
+
if (s.score % SHARDS_EVERY === 0) s.shards.push(newShard(s, rng))
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// shards drift across the field, turning a little towards the player, and bounce off its edges
|
|
149
|
+
const pace = 1.2 + s.score * 0.04
|
|
150
|
+
for (const shard of s.shards) {
|
|
151
|
+
const want = Math.atan2(p.z - shard.z, p.x - shard.x)
|
|
152
|
+
let turn = want - shard.heading
|
|
153
|
+
if (turn > Math.PI) turn -= Math.PI * 2; else if (turn < -Math.PI) turn += Math.PI * 2
|
|
154
|
+
shard.heading += clamp(turn, -0.4 * dt, 0.4 * dt)
|
|
155
|
+
shard.x += Math.cos(shard.heading) * pace * dt
|
|
156
|
+
shard.z += Math.sin(shard.heading) * pace * dt
|
|
157
|
+
if (Math.abs(shard.x) > FIELD) { shard.x = clamp(shard.x, -FIELD, FIELD); shard.heading = Math.PI - shard.heading }
|
|
158
|
+
if (Math.abs(shard.z) > FIELD) { shard.z = clamp(shard.z, -FIELD, FIELD); shard.heading = -shard.heading }
|
|
159
|
+
if (s.shield === 0 && far(shard, p) < 0.9) {
|
|
160
|
+
s.lives--
|
|
161
|
+
s.shield = 1.5 // a moment in which nothing more can hurt
|
|
162
|
+
const d = far(shard, p) || 0.01
|
|
163
|
+
p.vx = ((p.x - shard.x) / d) * 8; p.vz = ((p.z - shard.z) / d) * 8
|
|
164
|
+
emit({ type: 'hit', x: p.x, z: p.z, lives: s.lives })
|
|
165
|
+
if (s.lives <= 0) { s.status = 'over'; s.best = Math.max(s.best, s.score); s.steer = { x: 0, z: 0 }; emit({ type: 'over', score: s.score }) }
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
|
|
170
|
+
// what a player (or an agent) may do
|
|
171
|
+
actions: {
|
|
172
|
+
start(s, { rng, emit }) {
|
|
173
|
+
Object.assign(s, { status: 'playing', score: 0, lives: 3, shield: 2, player: { x: 0, z: 0, vx: 0, vz: 0 }, steer: { x: 0, z: 0 }, sparks: [], shards: [] })
|
|
174
|
+
for (let i = 0; i < 4; i++) s.sparks.push({ id: ++s.ids, ...somewhere(rng, s.player) })
|
|
175
|
+
s.shards.push(newShard(s, rng))
|
|
176
|
+
emit({ type: 'start' })
|
|
177
|
+
},
|
|
178
|
+
steer(s, _ctx, x, z) { s.steer.x = clamp(Number(x) || 0, -1, 1); s.steer.z = clamp(Number(z) || 0, -1, 1) },
|
|
179
|
+
},
|
|
180
|
+
|
|
181
|
+
// what the page shows and what an agent reads
|
|
182
|
+
report: (s) => ({
|
|
183
|
+
status: s.status, score: s.score, best: s.best, lives: s.lives, shield: s.shield,
|
|
184
|
+
player: { x: s.player.x, z: s.player.z },
|
|
185
|
+
sparks: s.sparks.map((k) => ({ id: k.id, x: k.x, z: k.z })),
|
|
186
|
+
shards: s.shards.map((k) => ({ id: k.id, x: k.x, z: k.z })),
|
|
187
|
+
}),
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
function newShard(s, rng) {
|
|
191
|
+
const at = somewhere(rng, s.player, 5)
|
|
192
|
+
return { id: ++s.ids, x: at.x, z: at.z, heading: rng.range(0, Math.PI * 2) }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* A player made of rules: go to the nearest spark, and lean away from any shard that is close.
|
|
197
|
+
* Tests and \`npm run balance\` play with it; it sees only what report() gives, as an agent would.
|
|
198
|
+
*/
|
|
199
|
+
export function advise(report) {
|
|
200
|
+
if (report.status !== 'playing') return { act: 'start' }
|
|
201
|
+
const p = report.player
|
|
202
|
+
let best = null
|
|
203
|
+
for (const spark of report.sparks) if (!best || far(spark, p) < far(best, p)) best = spark
|
|
204
|
+
let x = best ? best.x - p.x : 0, z = best ? best.z - p.z : 0
|
|
205
|
+
const len = Math.hypot(x, z) || 1
|
|
206
|
+
x /= len; z /= len
|
|
207
|
+
for (const shard of report.shards) {
|
|
208
|
+
const d = far(shard, p)
|
|
209
|
+
if (d < 2.4) { const push = (2.4 - d) * 1.6; x += ((p.x - shard.x) / (d || 0.01)) * push; z += ((p.z - shard.z) / (d || 0.01)) * push }
|
|
210
|
+
}
|
|
211
|
+
return { act: 'steer', x: clamp(x, -1, 1), z: clamp(z, -1, 1) }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The game is over. */
|
|
215
|
+
export const done = (report) => report.status === 'over'
|
|
216
|
+
`;
|
|
217
|
+
|
|
218
|
+
// ─── the page ───────────────────────────────────────────────────────────────────
|
|
219
|
+
|
|
220
|
+
const GAME = `// The page: it shows what the rules say and passes on what the player does.
|
|
221
|
+
//
|
|
222
|
+
// One frame() callback moves the rules on and copies their report into state; everything on
|
|
223
|
+
// screen is bound to that state. Sounds and sparks are set off by what the rules say happened
|
|
224
|
+
// (their events), so the rules never know there is a screen.
|
|
225
|
+
//
|
|
226
|
+
// An agent can play too: ai:readable is what it may see, ai:actionable what it may do.
|
|
227
|
+
// clarity.game().act('start') (src/main.js opens that door)
|
|
228
|
+
|
|
229
|
+
import { Scene, Mesh, Group, HemisphereLight, DirectionalLight, PointLight, Environment, Particles, createQuality, accessible } from '@clarity-js/gl'
|
|
230
|
+
import { frame } from '@ozsarman/clarityjs/game-loop'
|
|
231
|
+
import { createInput, createTilt, vibrate } from '@ozsarman/clarityjs/input'
|
|
232
|
+
import { audio, sfx, tune } from '@clarity-js/audio'
|
|
233
|
+
import { createGame, FIELD } from './rules.js'
|
|
234
|
+
|
|
235
|
+
component Game() {
|
|
236
|
+
state status = "ready"
|
|
237
|
+
state score = 0
|
|
238
|
+
state best = 0
|
|
239
|
+
state lives = 3
|
|
240
|
+
state shield = 0
|
|
241
|
+
state player = { x: 0, z: 0 }
|
|
242
|
+
state sparks = []
|
|
243
|
+
state shards = []
|
|
244
|
+
state spin = 0
|
|
245
|
+
state sound = true
|
|
246
|
+
state tilting = false
|
|
247
|
+
state said = ""
|
|
248
|
+
state touch = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches
|
|
249
|
+
ref stickEl
|
|
250
|
+
|
|
251
|
+
computed hearts = "♥".repeat(Math.max(0, lives))
|
|
252
|
+
computed camera = { fov: 46, position: [player.x * 0.4, 13, player.z * 0.4 + 9.5], lookAt: [player.x * 0.4, 0, player.z * 0.4 + 0.4] }
|
|
253
|
+
|
|
254
|
+
ai:readable = [status, score, lives, player, sparks, shards]
|
|
255
|
+
ai:actionable = [start, steer]
|
|
256
|
+
|
|
257
|
+
const game = createGame({ seed: Date.now() % 100000 })
|
|
258
|
+
const input = createInput()
|
|
259
|
+
const tilt = createTilt(input, { max: 25 })
|
|
260
|
+
const quality = createQuality()
|
|
261
|
+
const caught = audio.sound(sfx.coin(2))
|
|
262
|
+
const hurt = audio.sound(sfx.hurt(1))
|
|
263
|
+
const began = audio.sound(sfx.powerup(3), { volume: 0.6 })
|
|
264
|
+
const ended = audio.sound(tune("E4 C4 A3 -", { step: 0.16, wave: "triangle", volume: 0.35 }), { name: "over" })
|
|
265
|
+
let burst = null
|
|
266
|
+
let agent = false
|
|
267
|
+
let sx = 0
|
|
268
|
+
let sz = 0
|
|
269
|
+
|
|
270
|
+
action start() {
|
|
271
|
+
game.start()
|
|
272
|
+
show() // at once, not at the next frame: an agent that holds the clock sees what its move did
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
action steer(x, z) {
|
|
276
|
+
agent = true // an agent has taken the controls: the keys stand back until the next start by hand
|
|
277
|
+
game.steer(x, z)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function play() {
|
|
281
|
+
agent = false
|
|
282
|
+
sx = 0
|
|
283
|
+
sz = 0
|
|
284
|
+
audio.unlock()
|
|
285
|
+
game.start()
|
|
286
|
+
show()
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// what the rules say, copied into state: everything on screen follows from here
|
|
290
|
+
function show() {
|
|
291
|
+
const r = game.report()
|
|
292
|
+
status = r.status
|
|
293
|
+
score = r.score
|
|
294
|
+
best = r.best
|
|
295
|
+
lives = r.lives
|
|
296
|
+
shield = r.shield
|
|
297
|
+
player = r.player
|
|
298
|
+
sparks = r.sparks
|
|
299
|
+
shards = r.shards
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function tick(dt) {
|
|
303
|
+
spin = spin + dt
|
|
304
|
+
if (!agent) {
|
|
305
|
+
const x = input.axis("x").peek(), z = input.axis("y").peek()
|
|
306
|
+
if (x !== sx || z !== sz) { sx = x; sz = z; game.steer(x, z) } // told only when it changes: every move is kept in the game's log
|
|
307
|
+
}
|
|
308
|
+
game.step(Math.min(dt, 0.05))
|
|
309
|
+
// what happened this frame: sounds, a burst of sparks, a buzz
|
|
310
|
+
for (const e of game.events.splice(0)) {
|
|
311
|
+
if (e.type === "spark") { caught.play({ rate: [0.96, 1.06] }); said = "Spark caught. Score " + e.score; if (burst) { burst.node.position = [e.x, 0.6, e.z]; burst.emit(36) } }
|
|
312
|
+
else if (e.type === "hit") { hurt.play(); vibrate(60); said = "Hit by a shard. Lives left: " + e.lives }
|
|
313
|
+
else if (e.type === "start") { began.play(); said = "The game has begun" }
|
|
314
|
+
else if (e.type === "over") { ended.play(); vibrate([40, 60, 120]); said = "Out of lives. Final score " + e.score }
|
|
315
|
+
}
|
|
316
|
+
show()
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function toggleSound() {
|
|
320
|
+
sound = !sound
|
|
321
|
+
audio.muted = !sound
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function useTilt() {
|
|
325
|
+
tilt.enable().then((on) => { tilting = on })
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
onMount {
|
|
329
|
+
frame((dt) => tick(dt))
|
|
330
|
+
input.onPress("Space", () => { if (status !== "playing") play() })
|
|
331
|
+
input.onPress("Enter", () => { if (status !== "playing") play() })
|
|
332
|
+
if (stickEl) input.joystick(stickEl)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
render {
|
|
336
|
+
<div class="game">
|
|
337
|
+
<Scene class="game-scene" quality={ quality } shadows antialias background="#0b1020"
|
|
338
|
+
fog={ { color: "#0b1020", near: 16, far: 40 } } camera={ camera }
|
|
339
|
+
a11y={ accessible } label="A dark field seen from above, with golden sparks to catch and blue shards to avoid" announce={ said }>
|
|
340
|
+
<Environment sky={ { top: "#1b2a6b", horizon: "#3a4c9a", ground: "#0b1020", strength: 0.5 } } />
|
|
341
|
+
<HemisphereLight color="#8fa4ff" groundColor="#0b0b18" intensity={ 0.5 } />
|
|
342
|
+
<DirectionalLight position={ [6, 14, 8] } intensity={ 1.6 } castShadow shadowCameraSize={ 11 } />
|
|
343
|
+
|
|
344
|
+
<Mesh name="field" geometry="ground" args={ [FIELD * 2 + 1.4, FIELD * 2 + 1.4] } color="#141b3a" roughness={ 0.9 } receiveShadow />
|
|
345
|
+
|
|
346
|
+
<Group name="player" position={ [player.x, 0.5, player.z] }>
|
|
347
|
+
<Mesh geometry="sphere" args={ [0.45, 4] } color="#d7f6ff" emissive={ shield > 0 && status === "playing" ? "#ff5577" : "#28c8ff" }
|
|
348
|
+
emissiveIntensity={ shield > 0 ? 1 + Math.sin(spin * 30) * 0.6 : 0.9 } roughness={ 0.3 } castShadow />
|
|
349
|
+
<PointLight color="#58dcff" intensity={ 6 } distance={ 6 } position={ [0, 0.8, 0] } />
|
|
350
|
+
</Group>
|
|
351
|
+
|
|
352
|
+
<list items={ sparks } key="id">
|
|
353
|
+
<Mesh name={ "spark-" + item.id } geometry="octahedron" args={ [0.3] } position={ [item.x, 0.6 + Math.sin(spin * 2.6 + item.id) * 0.12, item.z] }
|
|
354
|
+
rotation={ [0, spin * 1.8 + item.id, 0] } color="#ffe08a" emissive="#ffae00" emissiveIntensity={ 1.5 } castShadow />
|
|
355
|
+
</list>
|
|
356
|
+
|
|
357
|
+
<list items={ shards } key="id">
|
|
358
|
+
<Mesh name={ "shard-" + item.id } geometry="octahedron" args={ [0.5] } position={ [item.x, 0.62, item.z] }
|
|
359
|
+
rotation={ [spin * 1.2, spin * 2 + item.id, 0] } color="#9fd8ff" emissive="#2a6bff" emissiveIntensity={ 1.1 } castShadow />
|
|
360
|
+
</list>
|
|
361
|
+
|
|
362
|
+
<Particles count={ 400 } rate={ 0 } lifetime={ [0.3, 0.7] } velocity={ [0, 2.2, 0] } velocitySpread={ 2.4 } gravity={ [0, -6, 0] }
|
|
363
|
+
size={ [0.16, 0] } color={ ["#fff1b8", "#ff9d00"] } ref={ (p) => { burst = p } } />
|
|
364
|
+
</Scene>
|
|
365
|
+
|
|
366
|
+
<div class="hud">
|
|
367
|
+
<span class="hud-score" data-testid="score">{ score }</span>
|
|
368
|
+
<span class="hud-lives" aria-label={ lives + " lives" }>{ hearts }</span>
|
|
369
|
+
<button class="hud-btn" on:click={ toggleSound() } aria-pressed={ sound ? "true" : "false" }>{ sound ? "Sound on" : "Sound off" }</button>
|
|
370
|
+
</div>
|
|
371
|
+
|
|
372
|
+
<when cond={ status !== "playing" }>
|
|
373
|
+
<div class="card">
|
|
374
|
+
<h1>{ status === "over" ? "Out of lives" : "Catch the sparks" }</h1>
|
|
375
|
+
<when cond={ status === "over" }>
|
|
376
|
+
<p class="card-score">{ score + (score === 1 ? " spark" : " sparks") + " · best " + best }</p>
|
|
377
|
+
</when>
|
|
378
|
+
<p>{ "Gather the golden sparks. Keep clear of the blue shards: three touches and it is over." }</p>
|
|
379
|
+
<button class="card-btn" data-testid="start" on:click={ play() }>{ status === "over" ? "Play again" : "Start" }</button>
|
|
380
|
+
<p class="card-keys">{ touch ? "Drag the stick, or tilt the phone" : "Arrows, WASD or a gamepad · Space to start" }</p>
|
|
381
|
+
<when cond={ touch && !tilting }>
|
|
382
|
+
<button class="hud-btn" on:click={ useTilt() }>{ "Steer by tilting" }</button>
|
|
383
|
+
</when>
|
|
384
|
+
</div>
|
|
385
|
+
</when>
|
|
386
|
+
|
|
387
|
+
<div class="stick" ref={ stickEl } style={ touch ? "" : "display:none" }>
|
|
388
|
+
<i style={ \`transform:translate(\${input.stick.get().x * 30}px, \${input.stick.get().y * 30}px)\` }></i>
|
|
389
|
+
</div>
|
|
390
|
+
</div>
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
`;
|
|
394
|
+
|
|
395
|
+
const STYLES = `:root { color-scheme: dark; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; }
|
|
396
|
+
html, body, #app { margin: 0; height: 100%; background: #0b1020; color: #e8ecff; overflow: hidden; }
|
|
397
|
+
.game { position: relative; height: 100%; touch-action: none; user-select: none; -webkit-user-select: none; }
|
|
398
|
+
.game-scene { position: absolute; inset: 0; }
|
|
399
|
+
.hud { position: absolute; top: max(12px, env(safe-area-inset-top)); left: 16px; right: 16px; display: flex; align-items: center; gap: 16px; pointer-events: none; }
|
|
400
|
+
.hud-score { font-size: 2rem; font-weight: 700; font-variant-numeric: tabular-nums; min-width: 2ch; }
|
|
401
|
+
.hud-lives { color: #ff6b8a; font-size: 1.4rem; letter-spacing: 0.15em; flex: 1; }
|
|
402
|
+
.hud-btn { pointer-events: auto; font: inherit; font-size: 0.85rem; color: inherit; background: rgba(255, 255, 255, 0.08); border: 1px solid rgba(255, 255, 255, 0.25); border-radius: 999px; padding: 0.4rem 0.9rem; cursor: pointer; }
|
|
403
|
+
.card { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: min(86vw, 360px); padding: 1.6rem 1.8rem; text-align: center; background: rgba(11, 16, 32, 0.86); border: 1px solid rgba(143, 164, 255, 0.35); border-radius: 16px; backdrop-filter: blur(6px); }
|
|
404
|
+
.card h1 { margin: 0 0 0.4rem; font-size: 1.5rem; }
|
|
405
|
+
.card p { margin: 0.5rem 0; line-height: 1.45; color: #c3cbef; }
|
|
406
|
+
.card-score { font-size: 1.1rem; color: #ffe08a !important; }
|
|
407
|
+
.card-btn { font: inherit; font-weight: 700; font-size: 1.05rem; color: #0b1020; background: #ffd35a; border: 0; border-radius: 12px; padding: 0.7rem 2rem; margin: 0.6rem 0 0.2rem; cursor: pointer; }
|
|
408
|
+
.card-keys { font-size: 0.85rem; opacity: 0.8; }
|
|
409
|
+
.stick { position: absolute; left: 24px; bottom: max(24px, env(safe-area-inset-bottom)); width: 110px; height: 110px; border-radius: 50%; background: rgba(255, 255, 255, 0.06); border: 1px solid rgba(255, 255, 255, 0.25); }
|
|
410
|
+
.stick i { position: absolute; left: 50%; top: 50%; width: 46px; height: 46px; margin: -23px 0 0 -23px; border-radius: 50%; background: rgba(255, 255, 255, 0.35); }
|
|
411
|
+
@media (prefers-reduced-motion: reduce) { .card { backdrop-filter: none; } }
|
|
412
|
+
`;
|
|
413
|
+
|
|
414
|
+
// ─── the test ───────────────────────────────────────────────────────────────────
|
|
415
|
+
|
|
416
|
+
const TEST = `// The rules, played with no browser. \`npm test\`
|
|
417
|
+
import test from 'node:test'
|
|
418
|
+
import assert from 'node:assert/strict'
|
|
419
|
+
import { runSim, balance } from '@ozsarman/clarityjs/sim'
|
|
420
|
+
import { createGame, advise, done, FIELD } from '../src/rules.js'
|
|
421
|
+
|
|
422
|
+
test('nothing moves until the game is started', () => {
|
|
423
|
+
const game = createGame({ seed: 1 })
|
|
424
|
+
for (let i = 0; i < 120; i++) game.step(1 / 60)
|
|
425
|
+
const r = game.report()
|
|
426
|
+
assert.equal(r.status, 'ready')
|
|
427
|
+
assert.equal(r.sparks.length, 0)
|
|
428
|
+
})
|
|
429
|
+
|
|
430
|
+
test('the same seed plays the same game', () => {
|
|
431
|
+
const a = runSim(createGame, { seed: 7, seconds: 30, policy: advise })
|
|
432
|
+
const b = runSim(createGame, { seed: 7, seconds: 30, policy: advise })
|
|
433
|
+
const c = runSim(createGame, { seed: 8, seconds: 30, policy: advise })
|
|
434
|
+
assert.deepEqual(a.report, b.report)
|
|
435
|
+
assert.notDeepEqual(a.report.sparks, c.report.sparks)
|
|
436
|
+
})
|
|
437
|
+
|
|
438
|
+
test('steering moves the player, and the field keeps it in', () => {
|
|
439
|
+
const game = createGame({ seed: 2 })
|
|
440
|
+
game.start()
|
|
441
|
+
game.steer(1, 0)
|
|
442
|
+
for (let i = 0; i < 600; i++) game.step(1 / 60)
|
|
443
|
+
const r = game.report()
|
|
444
|
+
assert.ok(r.player.x > FIELD - 0.01 && r.player.x <= FIELD, 'held at the edge: ' + r.player.x)
|
|
445
|
+
})
|
|
446
|
+
|
|
447
|
+
test('a spark that is reached is caught, and another takes its place', () => {
|
|
448
|
+
const game = createGame({ seed: 3 })
|
|
449
|
+
game.start()
|
|
450
|
+
const spark = game.report().sparks[0]
|
|
451
|
+
Object.assign(game.state.player, { x: spark.x, z: spark.z })
|
|
452
|
+
game.step(1 / 60)
|
|
453
|
+
const r = game.report()
|
|
454
|
+
assert.equal(r.score, 1)
|
|
455
|
+
assert.equal(r.sparks.length, 4)
|
|
456
|
+
assert.ok(game.events.some((e) => e.type === 'spark'))
|
|
457
|
+
})
|
|
458
|
+
|
|
459
|
+
test('a shard costs a life, not twice in the same moment, and the third ends the game', () => {
|
|
460
|
+
const game = createGame({ seed: 4 })
|
|
461
|
+
game.start()
|
|
462
|
+
const touch = () => { const s = game.state; s.shield = 0; Object.assign(s.shards[0], { x: s.player.x + 0.2, z: s.player.z }); game.step(1 / 60) }
|
|
463
|
+
touch()
|
|
464
|
+
assert.equal(game.report().lives, 2)
|
|
465
|
+
Object.assign(game.state.shards[0], { x: game.state.player.x, z: game.state.player.z })
|
|
466
|
+
game.step(1 / 60)
|
|
467
|
+
assert.equal(game.report().lives, 2, 'shielded for a moment after a hit')
|
|
468
|
+
touch(); touch()
|
|
469
|
+
assert.equal(game.report().status, 'over')
|
|
470
|
+
assert.ok(done(game.report()))
|
|
471
|
+
})
|
|
472
|
+
|
|
473
|
+
test('on every seed a careful player catches sparks before the game ends', () => {
|
|
474
|
+
const { summary } = balance(createGame, { seeds: 24, seconds: 150, policy: advise, until: done, measure: (r) => ({ score: r.score }) })
|
|
475
|
+
assert.equal(summary.done, 24, 'every game comes to an end')
|
|
476
|
+
assert.ok(summary.time.min >= 12, 'nobody loses before they have played: the shortest game lasted ' + summary.time.min + ' s')
|
|
477
|
+
assert.ok(summary.measures.score.min >= 10, 'the weakest game: ' + JSON.stringify(summary.measures.score))
|
|
478
|
+
assert.ok(summary.measures.score.median >= 20, 'a usual game: ' + JSON.stringify(summary.measures.score))
|
|
479
|
+
})
|
|
480
|
+
`;
|
|
481
|
+
|
|
482
|
+
function readme(opts) {
|
|
483
|
+
return `# ${opts.projectName}
|
|
484
|
+
|
|
485
|
+
A small 3D game built with [Clarity.js](https://clarity-js.com): catch the sparks, keep clear of
|
|
486
|
+
the shards. It is a starting point: change the rules, the look and the sounds until it is yours.
|
|
487
|
+
|
|
488
|
+
\`\`\`bash
|
|
489
|
+
npm install
|
|
490
|
+
npm run dev # play it
|
|
491
|
+
npm test # the rules, played with no browser
|
|
492
|
+
npm run balance # 24 games on 24 seeds: how they went
|
|
493
|
+
npm run build # the page, ready to host (dist/)
|
|
494
|
+
\`\`\`
|
|
495
|
+
|
|
496
|
+
## How it is put together
|
|
497
|
+
|
|
498
|
+
| File | What it is |
|
|
499
|
+
|---|---|
|
|
500
|
+
| \`src/rules.js\` | The game itself: plain numbers and chance from a seed. No page, no clock. \`createGame()\`, a player made of rules (\`advise\`), and \`done\`. |
|
|
501
|
+
| \`src/Game.clarity\` | The page: a \`<Scene>\` bound to state, the HUD, the controls. Each frame it moves the rules on, copies their report into state, and turns their events into sounds, sparks and a buzz. |
|
|
502
|
+
| \`test/rules.test.js\` | Plays the rules in Node: the same seed gives the same game, a hit costs a life, a careful player scores on every seed. |
|
|
503
|
+
|
|
504
|
+
Keeping the rules apart from the page is what makes the rest possible: tests need no browser,
|
|
505
|
+
\`npm run balance\` can play dozens of games in a second, and a replay is a seed and a list of moves.
|
|
506
|
+
|
|
507
|
+
## What is in it
|
|
508
|
+
|
|
509
|
+
- **3D** by [\`@clarity-js/gl\`](https://www.npmjs.com/package/@clarity-js/gl): meshes, lights and shadows as markup, particles on the GPU, light from a sky, one dial for quality.
|
|
510
|
+
- **Input** from \`@ozsarman/clarityjs/input\`: arrows, WASD, a gamepad, an on-screen stick, and tilt on a phone. A hit makes the phone or the gamepad buzz.
|
|
511
|
+
- **Sound** by [\`@clarity-js/audio\`](https://www.npmjs.com/package/@clarity-js/audio): every sound is made from numbers, so there are no files to ship. It starts on the first tap, as browsers require.
|
|
512
|
+
- **Agents can play.** \`ai:readable\` lists what an agent may see and \`ai:actionable\` what it may do, and nothing else is open to it. Any agent that speaks MCP (Claude Code, Claude Desktop, Cursor …) plays through \`clarity mcp\`:
|
|
513
|
+
|
|
514
|
+
\`\`\`bash
|
|
515
|
+
npm run dev
|
|
516
|
+
npx clarity mcp --open http://localhost:5173 # as the agent's MCP server: { "command": "npx", "args": ["clarity", "mcp"] }
|
|
517
|
+
\`\`\`
|
|
518
|
+
|
|
519
|
+
It can read the game, act, hold the clock and step it frame by frame, ask what is on screen in words, and look at a picture. The same door is in the browser console: \`clarity.game().act('steer', 1, 0)\`.
|
|
520
|
+
- **A screen reader is told** what happens (a spark caught, a hit, the final score), through \`<Scene a11y announce>\`.
|
|
521
|
+
|
|
522
|
+
## Making it yours
|
|
523
|
+
|
|
524
|
+
- New rules go in \`src/rules.js\` first, with a test beside them. Emit an event for anything the page should react to.
|
|
525
|
+
- \`npm run balance\` after every change of numbers: it tells you whether the game is still fair on every seed, not only on the one you tried.
|
|
526
|
+
- A coding agent can do all of this with you: the Clarity skills (\`clarity-game\`, \`clarity-gl\`) say how.
|
|
527
|
+
`;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
module.exports = { gameFiles };
|
package/lib/templates.js
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* router: boolean, // file/-component router add-on
|
|
14
14
|
* i18n: boolean, // internationalization add-on
|
|
15
15
|
* testing: boolean, // clarity-js/test add-on
|
|
16
|
+
* game: boolean, // the game template (lib/game.js): it stands alone, the add-ons do not apply
|
|
16
17
|
* clarityDep: string, // value for the clarity-js dependency (version or file:path)
|
|
17
18
|
* }
|
|
18
19
|
*/
|
|
@@ -20,6 +21,7 @@
|
|
|
20
21
|
'use strict';
|
|
21
22
|
|
|
22
23
|
function buildFiles(opts) {
|
|
24
|
+
if (opts.game) return require('./game').gameFiles(opts);
|
|
23
25
|
const files = {};
|
|
24
26
|
const ext = opts.typescript ? 'ts' : 'js';
|
|
25
27
|
|
|
@@ -41,7 +43,7 @@ function buildFiles(opts) {
|
|
|
41
43
|
scripts.serve = 'node server.js --prod';
|
|
42
44
|
delete scripts.preview;
|
|
43
45
|
}
|
|
44
|
-
if (opts.testing) scripts.test = 'node --test
|
|
46
|
+
if (opts.testing) scripts.test = 'node --test';
|
|
45
47
|
if (opts.typescript) scripts.typecheck = 'tsc --noEmit';
|
|
46
48
|
|
|
47
49
|
files['package.json'] = JSON.stringify({
|