Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 | // nethack.js — Browser game bootstrap // Loaded by index.html when the user navigates from the shell to play NetHack. // Creates a NethackGame instance, connects it to the browser Terminal and // keyboard input, and runs the game loop. import { CLR_GRAY } from './terminal.js'; import { GameDisplay } from './game_display.js'; import { NethackGame } from './jsmain.js'; import { game } from './gstate.js'; import { setStartupPromptPhase } from './input.js'; import { moveloop_core, maybe_do_tutorial } from './allmain.js'; import { docrt, render_screen_output_to_display } from './display.js'; import { runShell } from '../shell/shell.js'; import { startRecording, saveKeylog, getKeylog } from './keylog.js'; import { vfsReadFile, vfsWriteFile } from './storage.js'; import { lookat, stripForLookup } from './pager.js'; import { ShellEscape, GameQuit, GameInterrupt } from './signals.js'; const SHELL_CONTEXT_KEY = 'shell_context'; // Parse URL parameters for deterministic replay. // ?seed=N — PRNG seed (default: random) // ?datetime=YYYYMMDDHHMMSS — pinned game datetime (default: none) // ?nethackrc=... — URL-encoded .nethackrc content (overrides VFS) // ?replay=1 — enable session replay mode (shows lore/welcome/tutorial) // ?logrng=1 — enable RNG logging (for parity debugger) function getUrlParams() { const params = new URLSearchParams(window.location.search); const seedStr = params.get('seed'); const seed = (seedStr && /^\d+$/.test(seedStr)) ? parseInt(seedStr) : Math.floor(Math.random() * 100000) + 1; const datetime = params.get('datetime') || null; const nethackrc = params.get('nethackrc') || null; const replay = params.get('replay') === '1'; const versionBanner = params.get('version') || null; const logRng = params.get('logrng') === '1'; return { seed, datetime, nethackrc, replay, versionBanner, logRng }; } // Build .nethackrc: browser defaults + user overrides from VFS. // Browser defaults are prepended so user options take precedence // (later OPTIONS= lines override earlier ones, same as C). function getNethackrc() { const browserDefaults = [ 'OPTIONS=!autopickup', 'OPTIONS=suppress_alert:3.4.3', 'OPTIONS=symset:DECgraphics', 'OPTIONS=showexp', 'OPTIONS=time', 'OPTIONS=lit_corridor', ].join('\n'); // Try user's .nethackrc from the shell VFS. // The shell's static .nethackrc node uses vfsPath '.nethackrc' // (see filesystem.js), so the VFS key is 'vfs:.nethackrc'. const userRc = vfsReadFile('.nethackrc') || vfsReadFile('.nethackrc.txt'); if (userRc) return browserDefaults + '\n' + userRc; return browserDefaults; } async function main() { const gameDiv = document.getElementById('game'); if (!gameDiv) return; // Create the browser game display inside #game (GameDisplay = Terminal + game properties) const display = new GameDisplay('game'); window.__nhDisplay = display; // for goToShell screen capture // Set up keyboard input on the Terminal — NetHack-specific key mapper // converts browser keys to game codes (arrows→hjkl, numpad, Meta, etc.) display.keyMapper = (e) => mapBrowserKeyToNhCode(e, game?.flags || {}); const urlParams = getUrlParams(); const seed = urlParams.seed; const nethackrc = urlParams.nethackrc || getNethackrc(); const datetime = urlParams.datetime || null; console.log(`NetHack starting with seed ${seed}${datetime ? ` datetime ${datetime}` : ''}`); // Create and start the game. // If the nethackrc pre-sets role/race/gender/align, chargen prompts // are skipped — same as C's behavior with OPTIONS=role:Valkyrie etc. const nhGame = new NethackGame({ seed, nethackrc, datetime, logRng: urlParams.logRng, }); // Expose for parent-frame access (parity debugger Phase 2) window.__nhGame = nhGame; // Wire hamburger menu hooks window.save_keylog = saveKeylog; window._newGame = () => { window.location.reload(); }; window._saveAndQuit = () => { // Save game state as a keylog that can be replayed saveGameState(seed, datetime, nethackrc); goToShell('Saving...'); }; // Enable startup prompts (lore, welcome, tutorial) so the player // sees the intro text and tutorial offer. Without this, the browser // skips those screens when role/race/gender/align are pre-set. // Replay mode also needs this to match session recordings. if (urlParams.replay || !urlParams.notutorial) { nhGame._forcePromptedStartup = true; // setStartupPromptPhase is set inside start() via _pendingDisplay if (urlParams.versionBanner) { nhGame.versionBanner = urlParams.versionBanner; } } // ^C handler: during chargen, exit directly to shell (no game state). // After game starts, prompt "Really quit?" like C NetHack's done1(). let gameStarted = false; const chargenInterruptHandler = (ev) => { if (!ev || gameStarted) return; if (ev.ctrlKey && !ev.altKey && !ev.metaKey && typeof ev.key === 'string' && ev.key.toLowerCase() === 'c') { ev.preventDefault(); goToShell(); } }; document.addEventListener('keydown', chargenInterruptHandler); display.onInterrupt = () => { if (!gameStarted) { goToShell(); } else { // TODO: inject GameInterrupt into the game loop // For now, Ctrl-C during gameplay is a no-op until // nhgetch reads from terminal.readKey directly } }; // Wire display before start() — nhgetch reads from game.nhDisplay during chargen nhGame._pendingDisplay = display; try { await nhGame.start(); // Start recording keystrokes for keylog download (after game object exists) startRecording(seed, datetime, nethackrc); // If chargen was quit, return to the simulated shell if (game._chargenQuit) { goToShell(); return; } gameStarted = true; document.removeEventListener('keydown', chargenInterruptHandler); document.body.classList.add('gameplay-active'); // Expose lookat, encyclopedia, and menu state for hover info panel window._gameLookat = lookat; window._gameMenuActive = () => !!game._menuActive; { const { encyclopediaLookup } = await import('./encyclopedia.js'); // lazy // lazy window._encyclopediaLookup = encyclopediaLookup; window._stripForLookup = stripForLookup; } { const { getBotlFieldAt } = await import('./botl_descriptions.js'); // lazy // lazy window._getBotlFieldAt = getBotlFieldAt; } // Returns the menu's screen rectangle {offx, offy, rows, cols, fullscreen} // or null if no menu is active. Used by hover to distinguish menu text // from visible map cells. window._gameMenuRect = () => { if (!game._menuActive) return null; const m = game._activeMenu; if (!m) return { offx: 0, rows: 24, fullscreen: true }; const fs = !!(m.forceOffx0 || (m.maxrow >= 24)); return { offx: fs ? 0 : (m.offx || 0), rows: fs ? 24 : (m.maxrow || 24), fullscreen: fs, }; }; await maybe_do_tutorial(); if (urlParams.replay) { game.promptedStartup = false; setStartupPromptPhase(false); } // Render the initial game screen await renderToTerminal(display); // Main game loop: each iteration processes one player command. // moveloop_core() awaits nhgetch() which awaits keyboard input, // so the browser repaints between turns. // Signals: ShellEscape (!) → subshell then resume, // GameQuit (#quit/S) → exit to shell, // GameInterrupt (^C) → interrupt to shell. const getch = null; // TODO: wire display.readKey for subshell gameLoop: while (true) { try { await moveloop_core(); // C ref: done() sets gameover=1 via nh_terminate. // After death/ascension, moveloop_core returns normally. if (game.program_state?.gameover || game.program_state?.exiting) { goToShell('Be seeing you...'); return; } } catch (e) { if (e instanceof ShellEscape) { // Enter subshell, then return to game await renderToTerminal(display); display.flush(); await runShell(display, getch, null, { subshell: true }); // Restore game screen after subshell exits await renderToTerminal(display); continue gameLoop; } if (e instanceof GameQuit) { await renderToTerminal(display); if (e.message === 'Saving...') { saveGameState(seed, datetime, nethackrc); } goToShell(e.message || 'Be seeing you...'); return; } if (e instanceof GameInterrupt) { // Like C NetHack ^C: show "Really quit?" prompt await renderToTerminal(display); display.putstr(0, 0, 'Really quit? [yn] (n) ', CLR_GRAY); display.flush(); const answer = await new Promise(resolve => { const handler = (ev) => { document.removeEventListener('keydown', handler); resolve(ev.key); }; document.addEventListener('keydown', handler); }); if (answer === 'y' || answer === 'Y') { goToShell(); return; } // User said no — restore game screen and continue await renderToTerminal(display); continue gameLoop; } if (e.message?.includes('not yet ported')) { console.warn('Unported feature:', e.message); } else { console.error('Game error:', e); display.putstr(0, 0, `Error: ${e.message}`, CLR_GRAY); display.flush(); break; } } await renderToTerminal(display); } } catch (e) { console.error('Game startup error:', e); console.error('Stack:', e.stack); display.putstr(0, 0, `Startup error: ${e.message}`, CLR_GRAY); display.putstr(0, 2, 'Press any key to return to shell.', CLR_GRAY); display.flush(); await new Promise(resolve => { document.addEventListener('keydown', resolve, { once: true }); }); goToShell(); } } // Render the current game state to the browser Terminal. // docrt() produces game._screen_output with ANSI escapes. // render_screen_output_to_display() parses ANSI codes, DEC graphics, // and colors, writing each cell through display.setCell. async function renderToTerminal(display) { try { // captureOnly=true: render for display without gameplay side-effects // (no setBotlx, no event logging). C doesn't call docrt here. await docrt(false, true); } catch (e) { return; } render_screen_output_to_display(display); // Position cursor on the hero if (game.u && game.level) { display.setCursor(game.u.ux - 1, game.u.uy + 1); // -1: map x is 1-based, grid col is 0-based; +1: message line row } display.flush(); } // Save game state as a replayable keylog in VFS. // On restore, the game replays all keystrokes from the save to reach // the same state deterministically (same seed + same keys = same game). function saveGameState(seed, datetime, nethackrc) { try { const keylog = getKeylog(); const save = JSON.stringify({ version: 1, seed, datetime, nethackrc, keys: keylog.keys, savedAt: new Date().toISOString(), }); vfsWriteFile('/home/rodney/save.json', save); } catch (e) { console.error('Save failed:', e); } } function goToShell(bye) { // Transfer current screen contents so shell can display them const display = window.__nhDisplay; const screenRows = display ? captureScreenState(display) : []; const context = { app: 'nethack', rows: screenRows }; if (bye) context.bye = bye; localStorage.setItem(SHELL_CONTEXT_KEY, JSON.stringify(context)); window.location.href = '/shell/'; } function captureScreenState(display) { // Capture the current terminal content for shell to restore. // Terminal stores cells in display.grid[row][col].ch const rows = []; const grid = display.grid; if (!grid) return rows; for (let r = 0; r < 24; r++) { let line = ''; const row = grid[r]; if (!row) { rows.push(''); continue; } for (let c = 0; c < 80; c++) { line += row[c]?.ch || ' '; } rows.push(line); } return rows; } // Re-export signal classes for any module that imported from nethack.js export { ShellEscape, GameQuit, GameInterrupt }; /** * Convert a browser KeyboardEvent to NetHack char code. * Returns null when the key should be ignored. * C ref: curses_convert_keys (cursmisc.c:780-911) */ function mapBrowserKeyToNhCode(e, flags = {}) { // Ignore modifier-only keys if (e.key === 'Shift' || e.key === 'Control' || e.key === 'Alt' || e.key === 'Meta') { return null; } // Handle numeric keypad in number_pad mode const DOM_KEY_LOCATION_NUMPAD = (typeof KeyboardEvent !== 'undefined') ? KeyboardEvent.DOM_KEY_LOCATION_NUMPAD : 3; const numberPadMode = (typeof flags?.number_pad === 'number') ? flags.number_pad : (flags?.number_pad ? 1 : 0); const numberPadEnabled = numberPadMode > 0; if (e.location === DOM_KEY_LOCATION_NUMPAD && /^[0-9]$/.test(e.key)) { if (numberPadEnabled) { let digit = e.key; if (flags?.num_pad_mode & 2) { if (digit >= '1' && digit <= '3') digit = String.fromCharCode(digit.charCodeAt(0) + 6); else if (digit >= '7' && digit <= '9') digit = String.fromCharCode(digit.charCodeAt(0) - 6); } return digit.charCodeAt(0); } else { const numpadToVi = { '1': 'b', '2': 'j', '3': 'n', '4': 'h', '5': 'g', '6': 'l', '7': 'y', '8': 'k', '9': 'u', '0': '0', }; if (e.key in numpadToVi) return numpadToVi[e.key].charCodeAt(0); } } // Ctrl+key: C ref cmd.c C('x') = (x & 0x1f) if (e.ctrlKey && !e.altKey && !e.metaKey) { const code = e.key.toLowerCase().charCodeAt(0); if (code >= 97 && code <= 122) return code - 96; } // Meta (Alt)+key: C ref cmd.c M('x') = (x | 0x80) else if (e.altKey && !e.ctrlKey && !e.metaKey) { if (typeof e.code === 'string' && /^Key[A-Z]$/.test(e.code)) { return e.code[3].toLowerCase().charCodeAt(0) | 0x80; } if (e.key.length === 1) { const lower = e.key.toLowerCase(); if (lower >= 'a' && lower <= 'z') return lower.charCodeAt(0) | 0x80; return e.key.charCodeAt(0) | 0x80; } } else if (e.key === 'Escape') return 27; else if (e.key === 'Enter') return 13; else if (e.key === 'Backspace') return 8; else if (e.key === ' ' && flags?.rest_on_space) return '.'.charCodeAt(0); else if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) { return e.key.charCodeAt(0); } // Arrow keys and navigation else if (!e.altKey && !e.metaKey) { const swapYZ = !!flags?.swap_yz; const shift = e.shiftKey; const ctrl = e.ctrlKey; let ch = null; switch (e.key) { case 'ArrowLeft': ch = numberPadEnabled ? '4' : 'h'; break; case 'ArrowRight': ch = numberPadEnabled ? '6' : 'l'; break; case 'ArrowUp': ch = numberPadEnabled ? '8' : 'k'; break; case 'ArrowDown': ch = numberPadEnabled ? '2' : 'j'; break; case 'Home': ch = numberPadEnabled ? '7' : (swapYZ ? 'z' : 'y'); break; case 'PageUp': ch = numberPadEnabled ? '9' : 'u'; break; case 'End': ch = numberPadEnabled ? '1' : 'b'; break; case 'PageDown': ch = numberPadEnabled ? '3' : 'n'; break; case 'Clear': ch = numberPadEnabled ? '5' : 'g'; break; case 'Tab': return 9; } if (ch !== null) { if (numberPadEnabled && (flags?.num_pad_mode & 2) && ch >= '1' && ch <= '9') { if (ch >= '1' && ch <= '3') ch = String.fromCharCode(ch.charCodeAt(0) + 6); else if (ch >= '7' && ch <= '9') ch = String.fromCharCode(ch.charCodeAt(0) - 6); } if (numberPadEnabled) return ch.charCodeAt(0); if (ctrl) return ch.charCodeAt(0) & 0x1f; if (shift) return ch.toUpperCase().charCodeAt(0); return ch.charCodeAt(0); } } return null; } // Wait for DOM, then start if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', main); } else { await main(); } |