All files / js rumors.js

60.33% Statements 219/363
51.42% Branches 18/35
40% Functions 6/15
60.33% Lines 219/363

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 36473x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 272x 272x 272x 49841x 272x 272x 49569x 49569x   272x 73x 73x 73x 267x 267x 267x 267x 267x 272x 272x 272x 272x 272x 267x 267x 267x 267x 267x 267x 267x 73x 73x 73x 73x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 10x 10x 10x 10x 15x 15x 5x 5x 5x 5x 15x     15x 15x 15x 15x 15x 15x   15x 1x 1x 1x 15x 15x     15x 15x 73x 73x 73x 1x 1x 1x 1x 1x 1x   1x           1x 1x 1x 1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x 73x 73x 73x 73x 252x 252x 252x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                         73x 73x 73x           73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                                                                                                                         73x 73x 73x 73x 73x 73x                         73x 73x 73x 73x 73x 73x 73x                   73x 73x                 73x 73x                   73x 73x 73x 73x 73x       73x 73x             73x 73x 73x 73x 72x 72x 72x 72x 72x  
// rumors.js — ported from nethack-c/patched/src/rumors.c
 
import { game } from './gstate.js';
import { rn2, rnd, pushRngLogEntry } from './rng.js';
 
import { You, impossible, pline, verbalize } from './pline.js';
import { exercise } from './attrib.js';
import { Blind, is_fainted } from './macros.js';
import {
    ACH_ORCL, A_WIS, BOGUSMONFILE, BUFSZ, BY_COOKIE, BY_ORACLE, BY_OTHER, BY_PAPER, COLNO, ECMD_OK, ECMD_TIME, ENGRAVEFILE, EPITAPHFILE, LOW_PM, MALE, MD_PAD_RUMORS, NHW_TEXT, NUM_MGENDERS, ORACLEFILE, QBUFSZ, RUMORFILE, SEEK_CUR, SEEK_END, SEEK_SET, WIN_ERR
} from './const.js';
import { RUMORS_FILE_TEXT } from './rumor_data.js';
import { parseRumorsFile } from './hacklib.js';
import { G_UNIQ, M2_PNAME, NUMMONS, mons } from './monsters.js';
import { BOGON_CODES, BOGUSMONS, bogon_is_pname, type_is_pname } from './do_name.js';
import { the_unique_pm } from './objnam.js';
import { tty_display_nhwindow } from './display.js';
import { more_experienced, newexplevel } from './exper.js';
import { money_cnt } from './hack.js';
import { eos, lowc, strchr, unpadline, xcrypt } from './hacklib.js';
import { record_achievement } from './insight.js';
import { currency } from './invent.js';
import { Monnam } from './mon.js';
import { money2mon } from './shk.js';
import { SetVoice } from './sounds.js';
 
// Parse encrypted rumors file at module init — gives us decrypted texts
// plus actual file byte lengths for C-parity RNG offset simulation.
const _rumorData = parseRumorsFile(RUMORS_FILE_TEXT);
const TRUE_RUMORS = _rumorData.trueTexts;
const FALSE_RUMORS = _rumorData.falseTexts;
const _trueLineBytes = _rumorData.trueLineBytes;
const _falseLineBytes = _rumorData.falseLineBytes;
const _trueRange = _rumorData.trueSize;
const _falseRange = _rumorData.falseSize;
 
// Re-export for consumers
export { TRUE_RUMORS, FALSE_RUMORS };
 
// Do NOT cache `game` at module scope — game starts as null and is set later.
// Use `game` directly in all functions.
 
// ── get_rnd_line simulation ──
// C's get_rnd_line picks a random byte offset in the padded file chunk,
// skips to next line, decrypts, and unpads. We simulate the same RNG
// consumption with pre-decoded arrays and file byte lengths.
 
// Map byte offset to line index within file section
function offsetToLine(lineBytes, off) {
    let pos = 0;
    for (let i = 0; i < lineBytes.length; i++) {
        if (off < pos + lineBytes[i]) {
            return { line: i, remaining: lineBytes[i] - (off - pos) };
        }
        pos += lineBytes[i];
    }
    return { line: lineBytes.length - 1, remaining: 1 };
}
 
// Simulate C's get_rnd_line: consume RNG, return selected text
// C: get_rnd_line(fh, buf, bufsiz, rng, startpos, endpos, padlength)
function get_rnd_line_sim(texts, lineBytes, range, padlength, rng) {
    if (range < 1) return '';
 
    let lastInfo = null;
    for (let trylimit = 10; trylimit > 0; --trylimit) {
        const chunkoffset = rng(range);
        lastInfo = offsetToLine(lineBytes, chunkoffset);
        // C: if (!padlength || (unsigned) strlen(buf) <= padlength + 1) break
        if (!padlength || lastInfo.remaining <= padlength + 1) break;
    }
    if (!lastInfo) return '';
 
    // C reads the line AFTER the fseek position (skips partial line, uses next)
    // If past end, wraps to start
    const nextLine = (lastInfo.line + 1) % texts.length;
    return texts[nextLine] || '';
}
 
// C: getrumor(truth, rumor_buf, exclude_cookie)
// truth: 1=true, -1=false, 0=either
export function getrumor(truth, exclude_cookie) {
    const cookie_marker = "[cookie] ";
    let rumor_buf = '';
    let count = 0;
    let adjtruth;
 
    do {
        rumor_buf = '';
        // C: switch (adjtruth = truth + rn2(2))
        adjtruth = truth + rn2(2);
        let texts, lineBytes, range;
        switch (adjtruth) {
        case 2: // fallthrough (bogus input)
        case 1:
            texts = TRUE_RUMORS;
            lineBytes = _trueLineBytes;
            range = _trueRange;
            break;
        case 0: // fallthrough
        case -1:
            texts = FALSE_RUMORS;
            lineBytes = _falseLineBytes;
            range = _falseRange;
            break;
        default:
            impossible("strange truth value for rumor");
            return "Oops...";
        }
        rumor_buf = get_rnd_line_sim(texts, lineBytes, range, MD_PAD_RUMORS, rn2);
    } while (count++ < 50 && exclude_cookie
             && rumor_buf.startsWith(cookie_marker));
 
    if (count >= 50) {
        impossible("Can't find non-cookie rumor?");
    } else if (!game.in_mklev) {
        // C: exercise(A_WIS, (adjtruth > 0))
        exercise(A_WIS, (adjtruth > 0));
    }
 
    if (!exclude_cookie && rumor_buf.startsWith(cookie_marker)) {
        rumor_buf = rumor_buf.substring(cookie_marker.length);
    }
    return rumor_buf;
}
 
// C: outrumor(truth, mechanism)
export async function outrumor(truth, mechanism) {
    const fortune_msg = "This cookie has a scrap of paper inside.";
    const reading = (mechanism === BY_COOKIE || mechanism === BY_PAPER);
 
    if (reading) {
        // C: if (is_fainted() && mechanism == BY_COOKIE) return;
        if (is_fainted() && mechanism === BY_COOKIE) {
            return;
        } else if (Blind()) {
            if (mechanism === BY_COOKIE)
                await pline(fortune_msg);
            await pline("What a pity that you cannot read it!");
            return;
        }
    }
 
    let line = getrumor(truth, reading ? false : true);
    if (!line)
        line = "NetHack rumors file closed for renovation.";
 
    switch (mechanism) {
    case BY_ORACLE:
        // C: pline("True to her word, the Oracle %ssays: ", ...)
        await pline("True to her word, the Oracle %ssays: ",
              (!rn2(4) ? "offhandedly "
                       : (!rn2(3) ? "casually "
                                  : (rn2(2) ? "nonchalantly " : ""))));
        // C: SetVoice(...); verbalize1(line); — SetVoice not ported
        await verbalize(line);
        return;
    case BY_COOKIE:
        await pline(fortune_msg);
        // FALLTHROUGH to BY_PAPER
        // falls through
    case BY_PAPER:
        await pline("It reads:");
        break;
    }
    await pline(line);
}
 
// C: get_rnd_text(fname, buf, rng, padlength)
// In JS, we pass pre-decoded text arrays + file byte lengths.
// Used for engravings, epitaphs, and bogus monsters.
export function get_rnd_text(texts, lineBytes, chunksize, rng, padlength) {
    if (!texts || !texts.length) return '';
    return get_rnd_line_sim(texts, lineBytes, chunksize, padlength || 0, rng);
}
 
// C: outoracle(special, delphi)
// Not fully ported — depends on Oracle data file system (oracle_loc[], oracle_cnt)
// export async function outoracle(special, delphi) { /* TODO: needs oracle data */ }
 
// C: doconsult(oracl)
// Not fully ported — depends on money2mon, ynq, currency, Monnam, etc.
// export async function doconsult(oracl) { /* TODO: needs many unported functions */ }
 
// C: rumor_check() — wizard mode debug function
// export async function rumor_check() { /* TODO: wizard mode only */ }
 
// C: CapitalMon(word) — used by the() in objnam.c
// Checks if word is a capitalized non-unique monster type name
// that should be preceded by "the".
export function CapitalMon(word) {
    if (!word || word[0] === lowc(word[0]))
        return false;
    if (!game.CapMonsArray)
        init_CapMons();
    if (!game.CapMonsArray)
        return false;
    for (let i = 0; i < game.CapMonSiz - 1; ++i) {
        if (game.CapMonsArray[i] === word)
            return true;
    }
    return false;
}
 
// C: free_CapMons() — release memory for CapMons list
export function free_CapMons() {
    game.CapMonstCnt = 0;
    game.CapBogonCnt = 0;
    game.CapMonSiz = 0;
    game.CapMonsArray = null;
}
 
// ── Ported C infrastructure functions ──
 
// Static variables for CapitalMon (matching C statics in rumors.c)
 
 // CapMonstCnt + CapBogonCnt + 1 when non-zero
 
// the_unique_pm: imported from objnam.js
 
// C: init_CapMons(void)
// Two-pass scan: first count capitalized non-pname monster type names
// from mons[] and bogusmon data, then populate the CapMonsArray.
function init_CapMons() {
    if (game.CapMonsArray) // sanity precaution
        free_CapMons();

    for (let pass = 1; pass <= 2; ++pass) {
        game.CapMonstCnt = 0;
        game.CapBogonCnt = 0;

        // Gather applicable actual monsters from mons[]
        // C iterates pmnames[MALE..NUM_MGENDERS-1]; JS mons[] has single mname
        for (let mndx = LOW_PM; mndx < NUMMONS; ++mndx) {
            const mptr = mons[mndx];
            if ((mptr.geno & G_UNIQ) !== 0 && !the_unique_pm(mptr))
                continue;
            // In C, iterates pmnames[MALE] through pmnames[NUM_MGENDERS-1].
            // JS mons[] only has mname (equivalent to pmnames[NEUTRAL]).
            const nam = mptr.mname;
            if (nam && nam[0] !== lowc(nam[0])) {
                if (pass === 2)
                    game.CapMonsArray[game.CapMonstCnt] = nam;
                ++game.CapMonstCnt;
            }
        }

        // Gather applicable hallucinatory monsters from BOGUSMONS
        if (BOGUSMONS && BOGUSMONS.length) {
            for (let bi = 0; bi < BOGUSMONS.length; ++bi) {
                let xbuf = BOGUSMONS[bi];
                // BOGUSMONS entries are already decrypted and unpadded
                if (!xbuf || !xbuf.length) continue;

                let code, startp;
                if (BOGON_CODES.indexOf(xbuf[0]) < 0) {
                    code = '\0';
                    startp = xbuf;
                } else {
                    code = xbuf[0];
                    startp = xbuf.substring(1);
                }

                if (startp.length > 0
                    && startp[0] !== lowc(startp[0])
                    && !bogon_is_pname(code)) {
                    if (pass === 2)
                        game.CapMonsArray[game.CapMonstCnt + game.CapBogonCnt] = startp;
                    ++game.CapBogonCnt;
                }
            }
        }

        // Finish the current pass
        if (pass === 1) {
            game.CapMonSiz = game.CapMonstCnt + game.CapBogonCnt + 1; // +1: terminator
            game.CapMonsArray = new Array(game.CapMonSiz);
        } else {
            // Terminator; not strictly needed in JS
            game.CapMonsArray[game.CapMonSiz - 1] = null;
        }
    }
}
 
// C: unpadline(char *line)
// makedefs pads short rumors, epitaphs, engravings, and hallucinatory
// monster names with trailing underscores; strip those off
// C: init_rumors(dlb *fp)
// In JS, rumors are parsed from encrypted rumor_data.js at module init.
function init_rumors() {
    if (_trueRange > 0 && _falseRange > 0) {
        game.true_rumor_size = _trueRange;
        game.true_rumor_start = 0;
        game.true_rumor_end = _trueRange;
        game.false_rumor_size = _falseRange;
        game.false_rumor_start = _trueRange;
        game.false_rumor_end = _trueRange + _falseRange;
    } else {
        game.true_rumor_size = -1; // init failed
    }
}
 
// C: get_rnd_line — lower-level version used by init_rumors path.
// Now delegates to the shared get_rnd_line_sim which uses file byte lengths.
// Texts are already decrypted and unpadded by parseRumorsFile.
 
// C: init_oracles(dlb *fp)
// In JS, oracle data is pre-loaded; sets up oracle_cnt and oracle_loc
function init_oracles() {
    // Oracle data in JS is handled via pre-loaded arrays.
    // In C, this reads count and byte offsets from the oracle file header.
    if (!game.oracle_cnt) {
        game.oracle_cnt = 0;
        game.oracle_loc = null;
    }
    game.oracle_flg = 1;
}
 
// C: save_oracles(NHFILE *nhfp)
function save_oracles() {
    // Capture oracle state for serialization
    const data = {
        oracle_cnt: game.oracle_cnt || 0,
        oracle_loc: game.oracle_loc ? [...game.oracle_loc] : null,
    };
    return data;
}
 
// C: restore_oracles(NHFILE *nhfp)
function restore_oracles(data) {
    if (data) {
        game.oracle_cnt = data.oracle_cnt || 0;
        if (game.oracle_cnt && data.oracle_loc) {
            game.oracle_loc = [...data.oracle_loc];
            game.oracle_flg = 1; // no need to call init_oracles()
        }
    }
}
 
// C: others_check(const char *ftype, const char *file, winid *winp)
// In C, this opens a data file, reads first line, checks it matches
// the expected ftype header (e.g. "Engravings:", "Epitaphs:").
// In JS with pre-loaded data arrays, file validation is not needed.
function others_check(ftype, file, winp) {
    // No-op in JS — data files are pre-decoded arrays
}
 
// C: couldnt_open_file(const char *filename)
function couldnt_open_file(filename) {
    // C suppresses "saving and restoring might fix this" from impossible()
    // by temporarily clearing program_state.something_worth_saving.
    // In JS we just call impossible directly.
    impossible("Can't open '%s' file.", filename);
}
 
// is_fainted: imported from macros.js
 
export function init_rumors_globals() {
    game.CapMonstCnt = 0;
    game.CapBogonCnt = 0;
    game.CapMonSiz = 0;
    game.CapMonsArray = null;
}