Play Doom deathmatch while Claude works, and get handed back when it's done

A Claude Code plugin that drops you into Doom deathmatch while Claude works, and hands you back when it's done.


When Claude has been working for two seconds, a pane opens beside the transcript and you drop into a free-for-all on a shared server with everyone else who is waiting on Claude. When Claude finishes there's a three-second countdown and you're handed back. If Claude needs you, say for a permission prompt, you're handed back at once and dropped in again after you answer.
It's Odamex with Freedoom's maps, with monsters left in so the server is never empty.
/plugin install intermission --marketplace jarrodwatts/intermission
/intermission
The first time, it downloads the game, about 20 MB.
To turn it off again, run /intermission off.
Rio is the one terminal on Windows that can show the game's pixels. Set it up once, before installing intermission:
winget install -e --id raphamorim.rio
If you install Rio some other way, add the Redistributable with winget install Microsoft.VCRedist.2015+.x64.
conpty.dll and OpenConsole.exe from Microsoft's ConPTY package next to rio.exe: curl.exe -L -o "$env:TEMP\conpty.zip" https://www.nuget.org/api/v2/package/Microsoft.Windows.Console.ConPTY
Expand-Archive "$env:TEMP\conpty.zip" "$env:TEMP\conpty" -Force
Copy-Item "$env:TEMP\conpty\runtimes\win-x64\native\conpty.dll", "$env:TEMP\conpty\build\native\runtimes\x64\OpenConsole.exe" "C:\Program Files\Rio"
Both files must be there: with conpty.dll alone, Rio falls back to the console host built into Windows, which strips the pictures out.
%USERPROFILE%\AppData\Local\rio\config.toml; set everywhere, other terminals would show stray characters in place of pictures: env-vars = ["CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1"]
claude, and install intermission as above.If /intermission doesn't appear once it's installed, your Claude Code may not load mods yet; add "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1" to the same env-vars list.
Click the game to play. The click also locks the mouse for turning; Esc or ⌘ releases it. On Windows, Esc or Alt releases it, and the cursor stays in sight while locked.
| | | | :- | :- | | Move | WASD or the arrow keys | | Turn | the mouse, once locked | | Fire | left click | | Run forward | hold right click | | Open doors | space | | Weapons | 1 to 7 |
If your terminal is too narrow for the pane to open by itself, a line above the prompt offers it instead: press 1.
The game connects over UDP to the intermission server at 157.245.140.115, under a random name such as QueuedMarine42. Nothing about your session, project or Claude's work is sent. Between rounds it stays connected as a silent spectator, and disconnects after five minutes away.
The mod runs Odamex without a window. Each frame goes into shared memory, or on Windows a temporary file, which the terminal paints into the pane, and the pane passes keys and clicks back. Terminals report key presses but not releases, so a key counts as held until its auto-repeat stops. The changes to Odamex are in engine/odamex.patch, applied to the commit in engine/odamex-commit.
The server is stock Odamex; deploy.sh builds and runs it on a droplet.
The mod is MIT, as in LICENSE. Odamex is GPL-2.0, and so are the changes to it in engine/. Freedoom is BSD-3-Clause.
hooks/register.js 568 lines1// intermission: drops you into Doom while Claude works and hands you back when
2// it's done, or as soon as it needs you.
3
4const PANE = 'intermission'
5const WIDTH = 640
6const HEIGHT = 360
7const DROP_IN_DELAY_MS = 2000
8const COUNTDOWN_SECONDS = 3
9const SERVER = '157.245.140.115:10666'
10// Between drop-ins the engine waits on the server as a spectator; after this
11// long it disconnects, so idle sessions don't hold the server's slots
12const AWAY_DISCONNECT_MS = 5 * 60 * 1000
13// Long enough for a slow connection; some networks never let it through at all
14const CONNECT_TIMEOUT_MS = 10 * 1000
15
16const RELEASES = 'https://github.com/jarrodwatts/intermission/releases/download'
17
18const NAME_STARTS = ['Idle', 'Bored', 'Queued', 'Pending', 'Async', 'Blocked', 'Lazy']
19const NAME_ENDS = ['Dev', 'Coder', 'Hacker', 'Intern', 'Marine', 'Imp']
20
21// Whether the person turned intermission on, and their name in the game, both
22// kept between sessions in $.store
23let isOn = false
24let name = null
25
26// Set at session start. Windows has no uname, no rm and no POSIX shared
27// memory, so it runs the built-in tools by path and gets frames as files.
28let isWindows = false
29let tempDir = '/tmp'
30let system32 = null
31
32// Where play stands:
33// idle not playing, whether or not Claude is working
34// waiting Claude is working; dropping in once the delay passes
35// offered the terminal was too narrow for the pane to open by itself, so
36// the band above the prompt offers a key that opens it
37// playing the pane is open and the engine runs
38// countdown Claude is done; closing when the count reaches zero
39let phase = 'idle'
40let isTurnRunning = false
41// Closed by hand during this turn, so stay out until the next one
42let isDismissed = false
43let isWelcomeOpen = false
44let timer = null
45let countdown = 0
46
47// The running engine's output stream, the newest frame it wrote, the file it
48// reads input from, the input region's last line, and the disconnect timer
49let engine = null
50let frame = null
51let inputPath = null
52let clientLine = '0'
53let awayTimer = null
54// Set once the server proved unreachable, so the rest of the session plays a
55// local game against monsters instead
56let isOffline = false
57// The engine download in flight, and what the welcome pane says about it
58let download = null
59let downloadStatus = null
60// Kills and deaths in the current or last round, as the engine reports them
61let score = null
62
63function cancelTimer() {
64 timer?.cancel()
65 timer = null
66}
67
68function armDropIn($) {
69 if (!isOn || !isTurnRunning || isDismissed || phase !== 'idle') return
70 phase = 'waiting'
71 timer = $.clock.after(DROP_IN_DELAY_MS, () => dropIn($))
72}
73
74async function dropIn($) {
75 if (phase !== 'waiting') return
76 timer = null
77 const surfaces = await $.session.surfaces()
78 if (!surfaces.includes('terminal') || !(await $.fs.exists(enginePath($.plugin.root))) || (await lacksRuntime($))) {
79 phase = 'idle'
80 return
81 }
82 const opened = await $.ui.open({ id: PANE, title: 'intermission', focus: true })
83 if (!opened.isPlaced) {
84 // A waiting pane would pop up later, long after the moment has passed.
85 // One the person opens appears at any width, so offer them a key instead.
86 $.ui.log('the pane waits for a wider terminal: ' + opened.reason, { to: 'debug' })
87 await $.ui.close({ id: PANE })
88 phase = 'offered'
89 $.ui.invalidate('ui.render')
90 return
91 }
92 await startPlaying($)
93}
94
95async function acceptOffer($) {
96 if (phase !== 'offered') return
97 const { isPlaced } = await $.ui.open({ id: PANE, title: 'intermission', focus: true })
98 if (isPlaced) await startPlaying($)
99}
100
101async function startPlaying($) {
102 phase = 'playing'
103 $.ui.invalidate('ui.render')
104 awayTimer?.cancel()
105 awayTimer = null
106 if (engine) await writeInput($)
107 else void runEngine($)
108}
109
110// Claude is done or needs the person before they took up an offer to play
111function withdrawOffer($) {
112 cancelTimer()
113 phase = 'idle'
114 $.ui.invalidate('ui.render')
115}
116
117// why, when given, heads the toast that sums up the round
118async function pullOut($, why) {
119 cancelTimer()
120 phase = 'idle'
121 if (why && score) $.ui.toast(why + ' · ' + scoreText(score))
122 await $.ui.close({ id: PANE })
123}
124
125function scoreText({ kills, deaths }) {
126 return kills + (kills === 1 ? ' kill, ' : ' kills, ') + deaths + (deaths === 1 ? ' death' : ' deaths')
127}
128
129function startCountdown($) {
130 phase = 'countdown'
131 countdown = COUNTDOWN_SECONDS
132 $.ui.invalidate('ui.render')
133 timer = $.clock.every(1000, () => {
134 countdown -= 1
135 if (countdown > 0) $.ui.invalidate('ui.render')
136 else void pullOut($, "Claude's done")
137 })
138}
139
140// The engine plays or spectates by the first number, and takes keys only in play
141async function writeInput($) {
142 if (!inputPath) return
143 const isPlaying = phase === 'playing' || phase === 'countdown'
144 await $.fs.write(inputPath, isPlaying ? '1 ' + clientLine + '\n' : '0 0\n')
145}
146
147// The pane closed, whoever closed it: spectate until the next drop-in
148async function goAway($) {
149 cancelTimer()
150 phase = 'idle'
151 isWelcomeOpen = false
152 frame = null
153 // The next input region counts its clicks from zero again
154 clientLine = '0'
155 if (!engine) return
156 await writeInput($)
157 awayTimer?.cancel()
158 awayTimer = $.clock.after(AWAY_DISCONNECT_MS, () => void stopEngine($))
159}
160
161async function stopEngine($) {
162 awayTimer?.cancel()
163 awayTimer = null
164 // Leaving the stream's loop is what stops the engine
165 if (engine) await engine.return()
166}
167
168function randomName() {
169 const pick = (words) => words[Math.floor(Math.random() * words.length)]
170 return pick(NAME_STARTS) + pick(NAME_ENDS) + (10 + Math.floor(Math.random() * 90))
171}
172
173// Claude is about to ask the person something, so they must see the prompt
174async function needsYou($) {
175 if (phase === 'waiting' || phase === 'offered') {
176 withdrawOffer($)
177 } else if (phase !== 'idle') {
178 await pullOut($, 'Claude needs you')
179 }
180}
181
182function enginePath(root) {
183 return isWindows ? root + '\\dist\\odamex.exe' : root + '/dist/odamex.app/Contents/MacOS/odamex'
184}
185
186// A file in the temporary directory, for the engine's settings and input
187function tempPath(file) {
188 return tempDir + (isWindows ? '\\' : '/') + file
189}
190
191// The release asset's platform, as release.yml names it
192async function enginePlatform($) {
193 // Windows 11 on Arm runs the x64 build under emulation
194 if (isWindows) return 'windows-x64'
195 const [system, arch] = (await $.process.run(['uname', '-sm'])).stdout.trim().split(' ')
196 if (system !== 'Darwin') throw new Error('it runs on macOS and Windows for now')
197 return 'macos-' + arch
198}
199
200// With no shell to run them through, Windows gets its built-in tools by path,
201// so a curl or tar from Git or another package manager never stands in
202function tool(name) {
203 return isWindows ? system32 + name + '.exe' : name
204}
205
206async function removeFile($, path) {
207 await $.process.run(isWindows ? [tool('cmd'), '/d', '/c', 'del', '/f', '/q', path] : ['rm', '-f', path])
208}
209
210// odamex.exe needs the Visual C++ runtime, which Windows doesn't come with;
211// started without it, Windows stops it with an error dialog
212const RUNTIME_NEEDED =
213 'The game needs the Microsoft Visual C++ Redistributable: winget install Microsoft.VCRedist.2015+.x64'
214
215async function lacksRuntime($) {
216 if (!isWindows) return false
217 return !(await $.fs.exists(system32 + 'vcruntime140_1.dll')) || !(await $.fs.exists(system32 + 'msvcp140_1.dll'))
218}
219
220// Each plugin version downloads the engine built for it, once
221function ensureEngine($) {
222 download ??= downloadEngine($).finally(() => {
223 download = null
224 })
225 return download
226}
227
228async function downloadEngine($) {
229 const root = $.plugin.root
230 const showStatus = (text) => {
231 downloadStatus = text
232 $.ui.invalidate('ui.render')
233 }
234 if (await $.fs.exists(enginePath(root))) {
235 if (await lacksRuntime($)) showStatus(RUNTIME_NEEDED)
236 return
237 }
238 try {
239 const platform = await enginePlatform($)
240 const { version } = JSON.parse(await $.fs.read(root + '/.claude-plugin/plugin.json'))
241 const dist = root + (isWindows ? '\\dist' : '/dist')
242 const archive = dist + (isWindows ? '\\engine.tar.gz' : '/engine.tar.gz')
243 showStatus('Downloading the game, about 40 MB…')
244 // --create-dirs makes dist, with no mkdir to call on Windows
245 const fetched = await $.process.run(
246 [
247 tool('curl'),
248 '-fsSL',
249 '--retry',
250 '2',
251 '--create-dirs',
252 '-o',
253 archive,
254 RELEASES + '/v' + version + '/intermission-engine-' + platform + '.tar.gz',
255 ],
256 { timeoutMs: 10 * 60 * 1000 },
257 )
258 if (fetched.exitCode !== 0) throw new Error(fetched.stderr.trim() || 'the download failed')
259 const unpacked = await $.process.run([tool('tar'), '-xzf', archive, '-C', dist])
260 await removeFile($, archive)
261 if (unpacked.exitCode !== 0) throw new Error(unpacked.stderr.trim() || 'the download was damaged')
262 showStatus((await lacksRuntime($)) ? RUNTIME_NEEDED : 'The game is ready.')
263 } catch (error) {
264 showStatus("Couldn't get the game: " + error.message)
265 }
266}
267
268function engineRequest(root, id) {
269 return {
270 argv: [
271 enginePath(root),
272 '-iwad', root + '/dist/freedoom2.wad',
273 // Its own settings, so a person's own Odamex setup is never touched
274 '-config', tempPath('intermission-' + id + '.cfg'),
275 '-width', String(WIDTH),
276 '-height', String(HEIGHT),
277 '+vid_fullscreen', '0',
278 '+vid_maxfps', '35',
279 // Odamex's macOS music player ignores volume changes, so it played on
280 // while muted between drop-ins; its built-in OPL synth mixes through SDL
281 '+snd_musicsystem', '4',
282 '+cl_name', name,
283 ...(isOffline ? ['+map', 'MAP01'] : ['+connect', SERVER]),
284 ],
285 env: {
286 SDL_VIDEODRIVER: 'dummy',
287 SDL_RENDER_DRIVER: 'software',
288 // A per-run name keeps two sessions' frames from colliding. On Windows
289 // it starts the path of each frame's file, in a folder the engine sweeps
290 INTERMISSION_FRAMES: isWindows ? tempPath('intermission-frames\\' + id + '-') : '/im' + id + '-',
291 INTERMISSION_INPUT: inputPath,
292 },
293 }
294}
295
296async function runEngine($) {
297 const id = Math.random().toString(36).slice(2, 6)
298 inputPath = tempPath('intermission-' + id + '.input')
299 await writeInput($)
300 score = { kills: 0, deaths: 0 }
301 engine = $.process.spawn(engineRequest($.plugin.root, id))
302 const startedAt = await $.clock.now()
303 let isConnected = isOffline
304 let isUnreachable = false
305 let pending = ''
306 let failure = null
307 try {
308 for await (const { stream, text } of engine) {
309 if (stream !== 'stdout') continue
310 // Pieces arrive as written, not as lines, which end in \r\n on Windows
311 const lines = (pending + text).split(/\r?\n/)
312 pending = lines.pop()
313 for (const line of lines) {
314 if (line === '@connected') {
315 isConnected = true
316 continue
317 }
318 if (!isConnected && (await $.clock.now()) - startedAt > CONNECT_TIMEOUT_MS) {
319 isUnreachable = true
320 break
321 }
322 const sentAway = /^@disconnected (.*)/.exec(line)
323 if (sentAway) {
324 failure = 'intermission was disconnected' + (sentAway[1] ? ': ' + sentAway[1] : '')
325 break
326 }
327 const scored = /^@score (\d+) (\d+)/.exec(line)
328 if (scored) {
329 score = { kills: Number(scored[1]), deaths: Number(scored[2]) }
330 $.ui.invalidate('ui.render')
331 continue
332 }
333 // A Windows frame is a file path, which may hold spaces
334 const match = /^@frame (.+) \d+ \d+$/.exec(line)
335 if (!match) continue
336 const isFirst = frame === null
337 frame = match[1]
338 if (isFirst) {
339 $.ui.invalidate('ui.render')
340 } else {
341 $.ui.blit({ requestId: PANE, key: 'view', source: frameSource(frame) }).catch(() => {})
342 }
343 }
344 // Leaving the loop is what stops the engine
345 if (failure || isUnreachable) break
346 }
347 } catch (error) {
348 $.ui.log('the game did not start: ' + error, { to: 'debug' })
349 failure = "intermission couldn't start the game"
350 } finally {
351 engine = null
352 frame = null
353 inputPath = null
354 }
355 if (isUnreachable) {
356 isOffline = true
357 if (phase === 'playing' || phase === 'countdown') {
358 $.ui.toast(
359 "Couldn't reach the game server. Your network may block UDP, as corporate VPNs like Zscaler do, so this is an offline game against monsters.",
360 { timeoutMs: 8000 },
361 )
362 void runEngine($)
363 }
364 return
365 }
366 // Ending on its own while someone plays means the engine quit, crashed or was
367 // sent away; while they're away, the next drop-in simply starts it again.
368 // It also ends when this module unloads, and then there's nothing to close.
369 if (phase === 'playing' || phase === 'countdown') {
370 try {
371 $.ui.toast(failure ?? 'intermission lost the game')
372 await pullOut($)
373 } catch {}
374 }
375}
376
377// Claude Code reads POSIX shared memory only, so on Windows each frame is a
378// file the terminal reads instead
379function frameSource(name) {
380 return isWindows
381 ? { file: name, format: 'rgb', width: WIDTH, height: HEIGHT }
382 : { shm: name, format: 'rgb', width: WIDTH, height: HEIGHT }
383}
384
385export function register(on) {
386 on('session.start', async ($, e, next) => {
387 // Every Windows process has OS=Windows_NT in its environment
388 isWindows = (await $.env.get('OS')) === 'Windows_NT'
389 if (isWindows) {
390 tempDir = await $.env.get('TEMP')
391 system32 = (await $.env.get('SystemRoot')) + '\\System32\\'
392 }
393 isOn = (await $.store.get('isOn')) === true
394 name = await $.store.get('name')
395 if (!name) {
396 name = randomName()
397 await $.store.set('name', name)
398 }
399 await $.command.register({
400 name: 'intermission',
401 description: 'Play Doom while Claude works',
402 argumentHint: '[off]',
403 })
404 return next(e)
405 })
406
407 on('command.run', { command: 'intermission' }, async ($, e) => {
408 if (e.args.trim() === 'off') {
409 isOn = false
410 await $.store.set('isOn', false)
411 if (phase !== 'idle') await pullOut($)
412 await stopEngine($)
413 return { text: 'intermission is off.' }
414 }
415 isOn = true
416 await $.store.set('isOn', true)
417 // Opening it yourself also lets it open by itself in narrower terminals
418 if (phase === 'idle') {
419 isWelcomeOpen = true
420 await $.ui.open({ id: PANE, title: 'intermission' })
421 }
422 void ensureEngine($)
423 return {}
424 })
425
426 on('turn.start', async ($, e, next) => {
427 isTurnRunning = true
428 isDismissed = false
429 if (isWelcomeOpen) {
430 isWelcomeOpen = false
431 await $.ui.close({ id: PANE })
432 }
433 if (phase === 'countdown') {
434 // A queued prompt started straight away, so keep playing
435 cancelTimer()
436 phase = 'playing'
437 $.ui.invalidate('ui.render')
438 }
439 armDropIn($)
440 return next(e)
441 })
442
443 on('turn.complete', async ($, e, next) => {
444 if (e.agentId) return next(e)
445 isTurnRunning = false
446 if (phase === 'waiting' || phase === 'offered') {
447 withdrawOffer($)
448 } else if (phase === 'playing') {
449 if (e.isAborted) await pullOut($)
450 else startCountdown($)
451 }
452 return next(e)
453 })
454
455 on('tool.check', async ($, e, next) => {
456 const result = await next(e)
457 // In auto mode an ask can go to the classifier instead of the person;
458 // pulling out anyway costs a moment, missing a real prompt costs more
459 if (e.tool_use_id && result.decision === 'ask') await needsYou($)
460 return result
461 })
462
463 on('tool.call', async ($, e, next) => {
464 if (e.tool === 'AskUserQuestion') await needsYou($)
465 const result = await next(e)
466 // Once an answered prompt lets Claude carry on, drop back in
467 armDropIn($)
468 return result
469 })
470
471 on('ui.close', async ($, e, next) => {
472 if (e.id !== PANE) return next(e)
473 if (e.origin?.kind === 'person' && isTurnRunning) isDismissed = true
474 await goAway($)
475 return next(e)
476 })
477
478 on('ui.message', async ($, e) => {
479 if (e.element !== 'input') return {}
480 clientLine = e.data.line
481 await writeInput($)
482 return {}
483 })
484
485 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
486 if (phase !== 'offered') return next(e)
487 const { Box, Button } = $.ui.resolve(e)
488 // Keep whatever other mods show in the band
489 const others = await next(e)
490 return Box({
491 flexDirection: 'column',
492 children: [
493 Button({ key: 'play', label: 'Play Doom while Claude works', hotkey: '1', plain: true, onPress: () => acceptOffer($) }),
494 ...(others ? [others] : []),
495 ],
496 })
497 })
498
499 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
500 if (phase === 'idle' || phase === 'waiting' || !score) return next(e)
501 return next({ ...e, props: { ...e.props, suffix: ' · ' + scoreText(score) + '…' } })
502 })
503
504 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
505 if (e.requestId !== PANE) return next(e)
506 const { Box, Text, Image, Client, Button } = $.ui.resolve(e)
507
508 if (isWelcomeOpen) {
509 return Box({
510 flexDirection: 'column',
511 gap: 1,
512 children: [
513 Text({ bold: true, children: ['intermission is on'] }),
514 Text({
515 children: [
516 'When Claude has been working for 2 seconds you drop into Doom here, and you get handed back when it is done or needs you.',
517 ],
518 }),
519 ...(downloadStatus ? [Text({ children: [downloadStatus] })] : []),
520 Text({ dimColor: true, children: ['/intermission off turns it off.'] }),
521 Button({
522 key: 'got-it',
523 label: 'Got it',
524 autoFocus: true,
525 onPress: async () => {
526 isWelcomeOpen = false
527 await $.ui.close({ id: PANE })
528 },
529 }),
530 ],
531 })
532 }
533
534 if (e.surface !== 'terminal') {
535 return Text({ children: ['intermission needs the terminal, in ' + (isWindows ? 'Rio.' : 'Ghostty or kitty.')] })
536 }
537 if (!frame) return Text({ children: [isOffline ? 'Starting an offline game…' : 'Joining the game as ' + name + '…'] })
538 // Terminal cells are about twice as tall as they are wide
539 const columns = Math.min(255, e.props.bodyColumns)
540 const rows = Math.max(1, Math.round((columns * HEIGHT) / WIDTH / 2))
541 const status =
542 phase === 'countdown'
543 ? Text({ bold: true, children: ["Claude's done · back in " + countdown] })
544 : Text({
545 dimColor: true,
546 children: [
547 'Click the game to play and lock the mouse · ' +
548 (isWindows ? 'Esc or Alt' : 'Esc or ⌘') +
549 ' releases it · WASD or arrows · left click fires · right click runs · space opens',
550 ],
551 })
552 return Box({
553 flexDirection: 'column',
554 children: [
555 Image({ key: 'view', source: frameSource(frame), columns, rows, alt: 'Doom' }),
556 // Laid over the picture, so clicks land on the game
557 Box({
558 position: 'absolute',
559 top: 0,
560 left: 0,
561 children: [Client({ key: 'input', module: './input.js', width: columns, height: rows })],
562 }),
563 status,
564 ],
565 })
566 })
567}
568hooks/input.js 77 lines1// Catches keys and clicks over the game picture and posts what is held, which
2// the hooks module writes to the engine's input file. Each click also asks the
3// engine to lock the cursor, which it then reads for mouse-look itself.
4//
5// The terminal reports presses, never releases. A key counts as held until
6// its auto-repeat stops: long after a single press, because the first repeat
7// comes late, and briefly once repeats are flowing. Mouse buttons do report
8// releases.
9
10const HOLD_AFTER_PRESS_MS = 550
11const HOLD_WHILE_REPEATING_MS = 120
12
13const MOUSE_FIRE = 0x20000000
14const KEY_FORWARD = 'w'.charCodeAt(0)
15
16const SPECIAL_KEYS = {
17 up: 0x40000052,
18 down: 0x40000051,
19 left: 0x40000050,
20 right: 0x4000004f,
21 return: 0x0d,
22 tab: 0x09,
23}
24
25function keyCode(key) {
26 if (SPECIAL_KEYS[key]) return SPECIAL_KEYS[key]
27 return key.length === 1 ? key.toLowerCase().charCodeAt(0) : null
28}
29
30export default function GameInput(props, surface) {
31 if (surface.state === undefined) {
32 const input = {
33 presses: new Map(), // key code -> { at, isRepeating }
34 buttons: new Set(),
35 clicks: 0,
36 posted: '',
37 }
38
39 surface.onKey((e) => {
40 const code = keyCode(e.key)
41 if (code === null) return
42 const now = Date.now()
43 const last = input.presses.get(code)
44 input.presses.set(code, { at: now, isRepeating: !!last && now - last.at < HOLD_AFTER_PRESS_MS })
45 })
46
47 surface.onPointer((e) => {
48 const code = e.button === 'left' ? MOUSE_FIRE : e.button === 'right' ? KEY_FORWARD : null
49 if (code === null) return
50 if (e.type === 'down') {
51 input.buttons.add(code)
52 input.clicks += 1
53 }
54 if (e.type === 'up') input.buttons.delete(code)
55 })
56
57 surface.every(30, () => {
58 const now = Date.now()
59 const keys = new Set(input.buttons)
60 for (const [code, press] of input.presses) {
61 const holdMs = press.isRepeating ? HOLD_WHILE_REPEATING_MS : HOLD_AFTER_PRESS_MS
62 if (now - press.at < holdMs) keys.add(code)
63 else input.presses.delete(code)
64 }
65 const line = [input.clicks, ...[...keys].sort()].join(' ')
66 if (line === input.posted) return
67 input.posted = line
68 surface.post({ line })
69 })
70
71 surface.setState(input)
72 }
73
74 const { Box } = surface.elements
75 return Box({ width: '100%', height: '100%' })
76}
77